顺序等待VS继续等待 [英] Sequential await VS Continuation await
问题描述
我想知道由两个(或多个)异步和从属(第一个必须完成才能执行第二个)操作组成的异步代码的最佳/正确方式是什么.
I was wondering what is the best/correct way of writing asynchronous code that is composed of two (or more) async and dependent (the first have to finish to execute second) operations.
带有异步/等待的示例:
Example with async/await:
await RunFirstOperationAsync();
await RunSecondOperationAsync();
具有延续性的示例:
await RunFirstOperationAsync()
.ContinueWith(t => RunSecondOperationAsync());
推荐答案
如果可能的话,您想使用await
.
You'd want to use await
if you possibly can.
ContinueWith
有很多问题.我在为什么ContinueWith
是危险",该内容建立在我先前在为什么StartNew
很危险(它们有很多相同的问题).
ContinueWith
has a number of issues. I describe this briefly in my blog post on why ContinueWith
is dangerous, which builds on my earlier blog post on why StartNew
is dangerous (they share many of the same issues).
尤其是:
-
ContinueWith
没有很好的默认TaskScheduler
.默认任务计划程序是TaskScheduler.Current
(不是TaskScheduler.Default
),并且如果需要,必须手动完成在当前SynchronizationContext
上的恢复. -
ContinueWith
具有非理想的默认选项.对于异步代码,至少需要DenyChildAttach
和ExecuteSynchronously
. -
ContinueWith
无法理解异步延续,通常需要额外的Unwrap
调用来解决此限制. -
ContinueWith
以令人惊讶的方式对待其CancellationToken
自变量.此博客中有关的更多信息我的帖子.
ContinueWith
does not have a good defaultTaskScheduler
. The default task scheduler isTaskScheduler.Current
(notTaskScheduler.Default
), and resuming on the currentSynchronizationContext
must be done by hand if desired.ContinueWith
has non-ideal default options. For asynchronous code, you would wantDenyChildAttach
andExecuteSynchronously
, at least.ContinueWith
does not understand asynchronous continuations, which generally requires an additionalUnwrap
call to work around this limitation.ContinueWith
treats itsCancellationToken
argument in a surprising way. More on that in this blog post of mine.
These arguments are all summarized on my blog post on Task continuations. await
does not have any of these drawbacks.
这篇关于顺序等待VS继续等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!