I have a simple async method with the signature:
public async Task<bool> AllowAccessAsync(string authenticatedUserToken)
When calling this method, I appear to have two options when assigning its result to a local variable:
bool response = null;
// option 1
await this.transportService.AllowAccessAsync(authenticatedUserToken).ContinueWith(task => response = task.Result);
// option 2
response = await this.transportService.AllowAccessAsync(authenticatedUserToken);
The first uses a continuation delegate to assign to the local variable, the second assigns the result directly to the variable.
Do these have the same result? Are there any advantages to either approach? Is there a better way to do this?
Edit:
@Servy points out correctly that since the
ContinueWith
is simply a projection of the result. This means that both operations are semantically equivalent, but exception wise they'll behave differently.Edit 2:
The below remark relate to the use of
async-await
vsContinueWith
, generally. Looking specifically at both examples as they both useasync-await
, definitely use the latter, as both contain state-machine generation, but the latter will propagate anAggregateException
in case an exception occurs.async-await
has the minimal overhead of producing a state-machine, whileContinueWith
doesn't. On the other hand, usingasync-await
lets you "feel" synchronous while actually being asynchronous, and saves you the verbosity ofContinueWith
. I would definitely go withasync-await
, though I advise you to research the right path of using it, as there can be unexpected pitifuls.