我想知道编写由两个(或多个)异步和依赖(第一个必须完成才能执行第二个)操作组成的异步代码的最佳/正确方法是什么。
异步/等待示例:
await RunFirstOperationAsync();
await RunSecondOperationAsync();
继续示例:
await RunFirstOperationAsync()
.ContinueWith(t => RunSecondOperationAsync());
你想用await
如果可以的话。
ContinueWith
有很多问题。我在我的博客文章中简要描述了这一点why ContinueWith很危险 http://blog.stephencleary.com/2013/10/continuewith-is-dangerous-too.html,它建立在我之前的博客文章之上why StartNew很危险 http://blog.stephencleary.com/2013/08/startnew-is-dangerous.html(他们有许多相同的问题)。
尤其:
-
ContinueWith
没有好的默认值TaskScheduler
。默认的任务调度程序是TaskScheduler.Current
(not TaskScheduler.Default
),并继续当前SynchronizationContext
如果需要,必须手工完成。
-
ContinueWith
有非理想的默认值options https://msdn.microsoft.com/en-us/library/system.threading.tasks.taskcontinuationoptions(v=vs.110).aspx。对于异步代码,您需要DenyChildAttach
and ExecuteSynchronously
, 至少。
-
ContinueWith
不理解异步延续,这通常需要额外的Unwrap
调用以解决此限制。
-
ContinueWith
对待它的CancellationToken
以一种令人惊讶的方式争论。更多相关内容在这篇博文中 http://blog.stephencleary.com/2015/03/a-tour-of-task-part-9-delegate-tasks.html我的。
这些论点都总结在我的关于任务延续的博客文章 http://blog.stephencleary.com/2015/01/a-tour-of-task-part-7-continuations.html. await
没有任何这些缺点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)