当当前的syncContext已经是threadPool上下文时,是否尝试捕获上下文?

时间:2017-06-16 01:41:17

标签: c# .net async-await

示例:

public async Task Method1()
{
        //uses ASPNetSynchronisationContext 

        await Method2().ConfigureAwait(false);

        //uses ThreadPoolContext as we didn't capture the context above
        await Method3();

       //uses ThreadPoolContext
        await Method4();
}

我的问题是,"等待Method3()"试图捕捉上下文?无论如何,Method4使用ThreadPool上下文。

1 个答案:

答案 0 :(得分:0)

答案取决于Method2是否返回完整或不完整的任务。

正如我在async intro中所描述的那样,await首先检查其参数以确定它是否已经完成,如果已经完成,那么它将继续执行< EM>同步。如果已完成,则await将异步执行,其中包括(Task s)捕获上下文。

因此,如果Method2检查它时await返回的任务尚未完成,那么await异步执行,则在线程池上下文中恢复; Method3Method4在线程池上下文中开始,并且它们的await在线程池上下文中恢复。

但是,如果Method2返回的任务在await检查它时完成,那么await同步动作,则保留在ASP.NET上下文中; Method3Method4在ASP.NET上下文中开始,并在ASP.NET上下文中显示它们的await

出于这个原因,我建议once one await uses ConfigureAwait(false) in a method, that all later awaits in that method also use ConfigureAwait(false)