所以我有一种方法可以将任务链接在一起以完成工作
var tasks = new List<Task>();
tasks.Add(DoWorkAsync(1));
tasks.Add(DoWorkAsync(2));
tasks.Add(DoWorkAsync(3));
tasks.Add(DoWorkAsync(4));
tasks.Add(DoWorkAsync(5));
tasks.Add(DoWorkAsync(6));
await Task.WhenAll(tasks.ToArray());
为了获得更好的性能/响应能力,我一直在使用 ConfigureAwait(false)
上面的方法不需要在与调用线程相同的同步上下文上运行。
ConfigueAwait(false)
链接时使用的正确方法是Tasks
什么,我是否需要ConfigureAwait
针对每个单独的任务使用和/或需要在Task.WhenAll
作为一个额外的问题...
ConfigureAwait
如果在等待之后没有任何代码运行,实际上是否会做任何事情(或提高性能/响应能力)?
Ok so from the comments and chaining a few other questions together I think I have a better understanding of when to use configure await...
All of the below suggestions presume your task does not need to return to the calling thread. i.e. you have a valid ConfigureAwait
use case
ConfigureAwait configures the await, not the Task - You only need to use ConfigureAwait
on the line where await
is used
From this answer: Using ConfigureAwait(false) on tasks passed in to Task.WhenAll() fails
You do need to use ConfigureAwait
even if it is the last line in the method
From This answer: Does Task.ConfigureAwait(false) on the last method line affect anything?
ConfigureAwait
doesn't need to be called when using ContinueWith
From this answer: ConfigureAwait(false) when using ContinueWith
Task.WhenAll
已包含的任务已使用ConfigureAwait
这让我的代码看起来像这样:
var tasks = new List<Task>();
tasks.Add(DoWorkAsync(1));
tasks.Add(DoWorkAsync(2));
tasks.Add(DoWorkAsync(3));
tasks.Add(DoWorkAsync(4));
tasks.Add(DoWorkAsync(5));
tasks.Add(DoWorkAsync(6));
await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false);
令我惊讶的ConfigureAwait
是,大多数社区似乎建议使用,尽管在谈论线程/异步/等待时从来没有真正提及。
额外信息: 为什么我要麻烦使用Task.ConfigureAwait(continueOnCapturedContext:false);?
我不是该领域的专家,我只是将其他问题联系在一起,因此,如果我错过了任何事情/遇到了什么错误,请随时加入。
我将短语(1)称为“
ConfigureAwait
配置await
,而不是Task
”。忽略ContinueWith
; 这是一个低级,危险的操作,几乎不应该在现代代码中使用。谢谢@StephenCleary。我为寻找更多避免方法而烦恼
ContinueWith
。您是否获得了有关其问题信息的链接/避免了它/避免选择/任何有效用例最好的选择
ContinueWith
是await
。为了正确使用,您始终必须通过TaskScheduler
。最后,传递委托延续而不只是继续该async
方法只是很尴尬。