【问题标题】:ConfigureAwait(false) on the single line单行上的 ConfigureAwait(false)
【发布时间】:2021-11-04 18:08:04
【问题描述】:

在单个代码行上写ConfigureAwait(false) 是否有意义,例如:

private async Task test()
{
    await Task.Run(() =>{}).ConfigureAwait(false);
}

如果Microsoft documentationConfigureAwait(false) 只影响方法“tail”。

async Task MyMethodAsync()
{
    // Code here runs in the original context.
    await Task.Delay(1000);
    // Code here runs in the original context.
    await Task.Delay(1000).ConfigureAwait(continueOnCapturedContext: false);
    // Code here runs without the original
    // context (in this case, on the thread pool).
}

【问题讨论】:

  • 你读过下一行吗?通过使用 ConfigureAwait,你可以启用少量的并行性:一些异步代码可以与 GUI 线程并行运行,而不是不断地用一些工作来纠缠它to do" - 除此之外,它不需要在调用线程上创建延续,从而为您提供少量的效率。简而言之,代码没问题,只要你了解它的作用,以及它会导致什么问题
  • Peter test 方法等待 Task.Run(() => { })MyMethodAsync 方法等待两个 Task.Delay(1000)。等待对象的类型和等待对象的数量的这种差异对您提出的问题是否重要?我问是因为我想了解你到底在问什么。
  • 如果这有什么作用取决于多种因素。此代码是否有 UI 线程或其他同步上下文?你应该阅读这个devblogs.microsoft.com/dotnet/configureawait-faq

标签: c# async-await


【解决方案1】:

ConfigureAwait(false) 仅对未完成的可等待对象(Task-like 类型)产生影响,并且仅在 SynchronizationContext 下产生影响。

第一个简单的例子,如果ConfigureAwait(false)被省略:

private async Task test()
{
    await Task.Run(() =>{});
}

如果test 方法在SynchronizationContext 下运行,则await 之后的继续将被发布到SynchronizationContext

更详细的解释请参考ConfigureAwait FAQ

【讨论】:

    猜你喜欢
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    相关资源
    最近更新 更多