ConfigureAwait pushes the continuation to a pool thread

前端 未结 3 1636
夕颜
夕颜 2020-11-28 15:12

Here is some WinForms code:

async void Form1_Load(object sender, EventArgs e)
{
    // on the UI thread
    Debug.WriteLine(new { where = \"before\", 
               


        
3条回答
  •  猫巷女王i
    2020-11-28 15:57

    I think it's easiest to think of this in a slightly different way.

    Let's say you have:

    await task.ConfigureAwait(false);
    

    First, if task is already completed, then as Reed pointed out, the ConfigureAwait is actually ignored and the execution continues (synchronously, on the same thread).

    Otherwise, await will pause the method. In that case, when await resumes and sees that ConfigureAwait is false, there is special logic to check whether the code has a SynchronizationContext and to resume on a thread pool if that is the case. This is undocumented but not improper behavior. Because it's undocumented, I recommend that you not depend on the behavior; if you want to run something on the thread pool, use Task.Run. ConfigureAwait(false) quite literally means "I don't care what context this method resumes in."

    Note that ConfigureAwait(true) (the default) will continue the method on the current SynchronizationContext or TaskScheduler. While ConfigureAwait(false) will continue the method on any thread except for one with a SynchronizationContext. They're not quite the opposite of each other.

提交回复
热议问题