c# - Difference between these two async implementations -


i using ef's async methods fetch data database. of time well. have come few objectcontextdisposed exceptions of late, , curious why solution works:

here original code threw objectcontextdisposed:

public task<list<string>> geteventparametermru(eventparameter parameter, int count = 20) {     using (var repo = new configurationrepository())     {         return repo.geteventparametermru(_currentworkpack, parameter, count)                  } } 

here new code doesn't throw:

public async task<list<string>> geteventparametermru(eventparameter parameter, int count = 20) {     using (var repo = new configurationrepository())     {         var result = await repo.geteventparametermru(_currentworkpack, parameter, count);         return result;     } } 

could explain me difference is, , why works?

just fyi, in usages of method, call await geteventparametermru()

thanks

geteventparametermru apparently method starts task retrieve data. geteventparametermru returns before operations on repo have been completed.

both version of code use using statement, translated try/finally block. in finally block, repo disposed.

in first version, return immediatly after calling geteventparametermru (starting task). means repo disposed immediatly while task using repo still running. when task accesses repo receive your

objectdisposedexception


in second version use await. compiler therefor translates whole method state machine. method returns control caller @ await statement, without passing finally block.
when task completes, execution of method continued after await statement.
repo only disposed when task has completed. don't objectdisposedexception.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo