What thread runs the code after the `await` keyword?

前端 未结 2 1917
夕颜
夕颜 2020-12-02 00:16

Let me just post a simple example:

    private void MyMethod()
    {
        Task task = MyAsyncMethod();
        task.Wait();
    }

    private async Task          


        
2条回答
  •  臣服心动
    2020-12-02 00:33

    Code as posted will "Deadlock" in Winform App if called from main thread because you're blocking the main thread with the Wait().

    But in console app this works. but how?

    Answer is hidden in the SynchronizationContext.Current. await captures the "SynchronizationContext" and when the task is completed it will continue in the same "SynchronizationContext".

    In winform app SynchronizationContext.Current will be set to WindowsFormsSynchronizationContext which will post to the call to "Message loop", but who is going to process that? out main thread is waiting in Wait().

    In console app SynchronizationContext.Current will not be set by default so it will be null when no "SynchronizationContext" available for await to capture so it will schedule the continuation to ThreadPool(TaskScheduler.Default which is ThreadpoolTaskScheduler) and so the code after await works(through threadpool thread).

    Aforementioned capturing behavior can be controlled using Task.ConfigureAwait(false); which will prevent winform app from deadlocking but code after await no longer runs in UI thread.

提交回复
热议问题