什么配置ConfigureAwait做什么? ASP.NET Web API 2

时间:2017-08-18 11:59:50

标签: .net asp.net-web-api async-await

我正在开发ASP.NET Web API 2应用程序。在我们用于每个异步请求的应用程序中:

ConfigureAwait(false);

我真的不明白它是什么意思。我在互联网上看了但仍然不明白它到底是做什么的?

1 个答案:

答案 0 :(得分:4)

要理解它,您需要了解Synchronization ContextThreading Models是什么。

从实际角度来看,让我们来看看规范的例子。您正在开发GUI应用程序(Win Forms或WPF)。你有专门的UI线程。 您必须在UI线程上更新UI,并且不要通过计算或等待某些响应来阻止UI线程。

ConfigureAwait async / await 有关。默认情况下, await 之后的代码将在捕获的UI线程上运行,

await DoAsync();
//UI updating code goes here. Will run on UI thread

如果指定ConfigureAwait(false)

,await之后的代码将在线程池上运行
await DoAsync().ConfigureAwait(false);
//CPU intensive operation. Will run on thread pool

就ASP.NET应用程序而言,您没有专用的UI线程。但同步上下文也很重要。 Understanding the SynchronizationContext in ASP.NET会向您提供详细信息。