顺序等待VS继续等待

时间:2016-04-22 15:04:35

标签: c# asp.net .net async-await

我想知道编写异步代码的最佳/正确方法是什么,该异步代码由两个(或多个)异步和依赖(第一个必须完成执行第二个)操作组成。

async / await示例:

var map = {};
var symbol1 = Symbol("prop");
var symbol2 = Symbol("prop"); // same name, different instance – so it's a different symbol!
map[symbol1] = 1;
map[symbol2] = 2; // doesn't override the previous symbol's value
console.log(map[symbol1] + map[symbol2]); // logs 3

延续示例:

await RunFirstOperationAsync();
await RunSecondOperationAsync();

1 个答案:

答案 0 :(得分:17)

如果可能,您可以使用await

ContinueWith有很多问题。我在why ContinueWith is dangerous的博客文章中对此进行了简要描述,该文章基于我之前在why StartNew is dangerous上发表的博客文章(他们有许多相同的问题)。

特别是:

  • ContinueWith没有良好的默认TaskScheduler。默认任务计划程序为TaskScheduler.Current(不是TaskScheduler.Default),如果需要,必须手动完成当前SynchronizationContext的恢复。
  • ContinueWith有非理想的默认options。对于异步代码,您至少需要DenyChildAttachExecuteSynchronously
  • ContinueWith无法理解异步延续,这通常需要额外的Unwrap调用来解决此限制。
  • ContinueWith以惊人的方式处理其CancellationToken参数。更多关于我的in this blog post

我的blog post on Task continuations总结了这些论点。 await没有任何这些缺点。