c# - Wrap async lambda to the async method -
i'm trying wrap operations contracts
try-catch block. problem ef context destroyed in same time scope. guess problem compiler doesn't know properly. catch block doesn't handle exceptions. sorry english, hope code show mean:
private static async task<t> surroundwithtrycatch<t>(action t, t response) t : baseresponse { try { await task.run(t); } catch (exception e) { response.success = false; response.errors.add(e.message); } return response; } public async task<createresponse> createasync(createrequest request) { var response = new createresponse(); return await surroundwithtrycatch(async delegate { var newuser = new applicationuser { username = request.username, email = request.email }; await database.usermanager.createasync(newuser, request.password); //some logic... await database.commitasync(); }, response); }
the problem in second line of createasync
method. usermanager
cleaned gc earlier. have objectdisposedexception
. database
iunitofwork
implementation , injected autofac
.
you're breaking await
chain - t
no longer returns task. since no longer have task, execution continue after first await
, rather after whole method done. think of await
return
- if don't return (and await
/wait for) task, lose chance @ synchronization.
instead, want pass func<task>
, , await directly:
private static async task<t> surroundwithtrycatch<t>(func<task> t, t response) t : baseresponse { try { await t(); } catch (exception e) { response.success = false; response.errors.add(e.message); } return response; } public async task<createresponse> createasync(createrequest request) { var response = new createresponse(); return await surroundwithtrycatch(async () => { var newuser = new applicationuser { username = request.username, email = request.email }; await database.usermanager.createasync(newuser, request.password); //some logic... await database.commitasync(); }, response); }
task.run
works, don't want anyway - code asynchronous, , (a guess) you're running in asp.net request, there's no benefit launching task wait on result of task. task.run
used doing cpu work in separate thread, want avoid in asp.net.
Comments
Post a Comment