async and await are single threaded Really?

前端 未结 2 909
孤街浪徒
孤街浪徒 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:06

    The async and await keywords don't cause additional threads to be created.

    Yes. It moves the CPU bound or I/O bound work to other thread from the thread pool of the process so that it is not executed on UI thread or current synchronization context, it does not create a new thread which is what meant in the MSDN description.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题