我想知道编写异步代码的最佳/正确方法是什么,该异步代码由两个(或多个)异步和依赖(第一个必须完成执行第二个)操作组成。
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();
答案 0 :(得分:17)
如果可能,您可以使用await
。
ContinueWith
有很多问题。我在why ContinueWith
is dangerous的博客文章中对此进行了简要描述,该文章基于我之前在why StartNew
is dangerous上发表的博客文章(他们有许多相同的问题)。
特别是:
ContinueWith
没有良好的默认TaskScheduler
。默认任务计划程序为TaskScheduler.Current
(不是TaskScheduler.Default
),如果需要,必须手动完成当前SynchronizationContext
的恢复。ContinueWith
有非理想的默认options。对于异步代码,您至少需要DenyChildAttach
和ExecuteSynchronously
。ContinueWith
无法理解异步延续,这通常需要额外的Unwrap
调用来解决此限制。ContinueWith
以惊人的方式处理其CancellationToken
参数。更多关于我的in this blog post。我的blog post on Task continuations总结了这些论点。 await
没有任何这些缺点。