【发布时间】:2021-11-04 18:08:04
【问题描述】:
在单个代码行上写ConfigureAwait(false) 是否有意义,例如:
private async Task test()
{
await Task.Run(() =>{}).ConfigureAwait(false);
}
如果Microsoft documentation 说ConfigureAwait(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