1

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?

1
  • 1
    It's really just syntactic sugar, when compiled, a normal Main method gets added that calls Main(args).GetAwaiter().GetResult();
    – DavidG
    Dec 10, 2020 at 15:30

1 Answer 1

5

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.

1
  • Perfect thanks, still not able to mark as accepted, will mark as accepted one it shows up. (2 day delay I think?) Dec 11, 2020 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.