Search code examples
c#multithreadingasynchronousasync-awaitclr

.NET async Main method thread


I am just wondering in an app without a SynchronizationContext (e.g. Console), how is async static Main(args) implemented. Is the start of the main method before any await a

  1. Threadpool thread, where the CLR itself has a dedicated thread which queues Main call onto the threadpool and synchronously waits for it to finish?

    OR

  2. Is it a dedicated starter thread, which gets compiled into a special state machine, to synchronously block the thread at each await. Or even maybe all awaits get combined into one and the main thread waits for this combined task to complete?


Solution

  • An async static Task Main method really just generates an entry point like this:

    public static void GeneratedEntryPoint(string[] args)
    {
        Main(args).GetAwaiter().GetResult();
    }
    

    So just like a normal synchronous Main method, it starts in a thread with no synchronization context. That means any continuations are executed on thread-pool threads. But the initial thread (which will execute any code until the first await expression that needs to schedule a continuations) is not a thread-pool thread itself.