温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Correct use of ConfigureAwait(false) when chaining tasks
asynchronous c# task

c# - 链接任务时正确使用ConfigureAwait(false)

发布于 2020-03-27 10:21:10

所以我有一种方法可以将任务链接在一起以完成工作

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如果在等待之后没有任何代码运行,实际上是否会做任何事情(或提高性能/响应能力)?

查看更多

查看更多

提问者
user1
被浏览
264
user1 2019-07-03 22:43

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

  1. 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

  2. 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?

  3. ConfigureAwait doesn't need to be called when using ContinueWith

    From this answer: ConfigureAwait(false) when using ContinueWith

  4. Task.WhenAll包含的任务已使用ConfigureAwait

    也是从这个答案:在传递给Task.WhenAll()的任务上使用ConfigureAwait(false)失败

这让我的代码看起来像这样:

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);?

我不是该领域的专家,我只是将其他问题联系在一起,因此,如果我错过了任何事情/遇到了什么错误,请随时加入。