async and await are single threaded Really?

前端 未结 2 911
孤街浪徒
孤街浪徒 2021-02-04 10:54

I created following code:

using System;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main()
                


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-04 11:13

    I explain how async and await work with threads and contexts on my blog. In summary, when await needs to wait for an asynchronous operation to complete, it will "pause" the current async method and (by default) capture a "context".

    When the asynchronous operation completes, that "context" is used to resume the async method. This "context" is SynchronizationContext.Current, unless it is null, in which case it is TaskScheduler.Current. In your case, the context ends up being the thread pool context, so the rest of the async method is sent to the thread pool. If you run the same code from the UI thread, the context would be the UI context, and all the async methods will resume on the UI thread.

提交回复
热议问题