c# - Does async Task method never throw? -
it appears async method captures exceptions task
method returns including thrown before first await
". in other words following code works intended , no exceptions thrown until line task.whenall
:
async task dosomethingasync(int i) { if (i == 2) throw new invalidoperationexception(); await task.delay(1000); } ... var tasks = new list<task>(); for(int = 0; < 3; ++i) { var t = dosomethingasync(i); // no awaits here tasks.add(t); } // wait tasks await task.whenall(tasks); // throws invalidoperation when other 2 tasks succeed
the question:
is behavior of async methods part of language spec or way implemented in current version of .net? can rely on behavior in code?
is behavior of async methods part of language spec
yes is. section 10.15.1 of c# 5 specification:
- if function body terminates result of uncaught exception (§8.9.5) exception recorded in return task put faulted state.
section 10.15.2 gives details of async methods returning void
:
if return type of async function void, evaluation differs above in following way: because no task returned, function instead communicates completion , exceptions current thread’s synchronization context. exact definition of synchronization context implementation-dependent, representation of “where” current thread running. synchronization context notified when evaluation of void-returning async function commences, completes successfully, or causes uncaught exception thrown.
admittedly don't think explicitly says call doesn't throw, believe intended interpretation of spec.
if want method throw if (say) preconditions aren't met, use normal async behaviour, can take same approach common iterator blocks:
public task foo(int someparameter) { // check preconditions here , throw - note isn't // async method, exceptions thrown synchronously. return fooimpl(someparameter); } private async task fooimpl(int someparameter) { // assume valid now. // normal async method implementation. }
Comments
Post a Comment