Jas*_*son 3 .net c# asynchronous task-parallel-library async-await
我有一个简单的异步方法与签名:
public async Task<bool> AllowAccessAsync(string authenticatedUserToken)
Run Code Online (Sandbox Code Playgroud)
调用此方法时,在将结果分配给局部变量时,我似乎有两个选项:
bool response = null;
// option 1
await this.transportService.AllowAccessAsync(authenticatedUserToken).ContinueWith(task => response = task.Result);
// option 2
response = await this.transportService.AllowAccessAsync(authenticatedUserToken);
Run Code Online (Sandbox Code Playgroud)
第一个使用continuation委托分配给局部变量,第二个将结果直接分配给变量.
这些结果是否相同?两种方法都有任何优势吗?有一个更好的方法吗?
这些结果是否相同?
编辑:
@Servy正确地指出,因为ContinueWith它只是结果的投影.这意味着两个操作在语义上都是等效的,但是例外的是它们的行为会有所不同.
两种方法都有任何优势吗?有一个更好的方法吗?
编辑2:
以下评论一般涉及async-awaitvs 的使用ContinueWith.特别注意它们都使用的两个示例async-await,明确使用后者,因为它们都包含状态机生成,但后者将传播AggregateException以防异常发生.
async-await生产状态机的开销最小,而ContinueWith不是.另一方面,使用async-await让你"感觉"同步,而实际上是异步,并节省你的冗长ContinueWith.我肯定会和async-await你一起去,虽然我建议你研究使用它的正确途径,因为可能有意外的可怜.