我了解在库代码中使用ConfigureAwait(false)
建议用于await
,以便后续代码不在调用方的执行上下文中运行,这可能是UI线程。我也知道出于同样的原因应该使用await Task.Run(CpuBoundWork)
而不是CpuBoundWork()
。
使用ConfigureAwait
的示例
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
});
}
这两种方法之间有什么区别?