问题描述
我知道建议在库代码中为 await
使用 ConfigureAwait(false)
以便后续代码不会在调用者的执行上下文中运行,这可能是一个 UI 线程.我也明白,出于同样的原因,应该使用 await Task.Run(CpuBoundWork)
而不是 CpuBoundWork()
.
I understand that it's recommended to use ConfigureAwait(false)
for await
s in library code so that subsequent code does not run in the caller's execution context, which could be a UI thread. I also understand that await Task.Run(CpuBoundWork)
should be used instead of CpuBoundWork()
for the same reason.
public async Task<HtmlDocument> LoadPage(Uri address)
{
using (var client = new HttpClient())
using (var httpResponse = await client.GetAsync(address).ConfigureAwait(false))
using (var responseContent = httpResponse.Content)
using (var contentStream = await responseContent.ReadAsStreamAsync().ConfigureAwait(false))
return LoadHtmlDocument(contentStream); //CPU-bound
}
带有 Task.Run
的示例public async Task<HtmlDocument> LoadPage(Uri address)
{
using (var client = new HttpClient())
using (var httpResponse = await client.GetAsync(address))
return await Task.Run(async () =>
{
using (var responseContent = httpResponse.Content)
using (var contentStream = await responseContent.ReadAsStreamAsync())
return LoadHtmlDocument(contentStream); //CPU-bound
});
}
这两种方法有什么区别?
What are the differences between these two approaches?
推荐答案
当你说 Task.Run
时,你是说你有一些 CPU 工作要做,这可能需要很长时间,所以它应该始终在线程池线程上运行.
When you say Task.Run
, you are saying that you have some CPU work to do that may take a long time, so it should always be run on a thread pool thread.
当您说 ConfigureAwait(false)
时,您是说该 async
方法的其余部分不需要原始上下文.ConfigureAwait
更像是一个优化提示;它并不总是意味着延续在线程池线程上运行.
When you say ConfigureAwait(false)
, you are saying that the rest of that async
method does not need the original context. ConfigureAwait
is more of an optimization hint; it does not always mean that the continuation is run on a thread pool thread.
这篇关于使用 ConfigureAwait(false) 和 Task.Run 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!