I'm trying to figure out how an async main method is started in C#. To do this I would like to create an example of a new Thread that is the same as the async main thread.
This is how it is done without async:
class Program
{
public static void Main(string[] args)
{
Thread t = new Thread(Main2)
{ IsBackground = false };
t.Start();
}
public static void Main2()
{
Console.WriteLine("Helloooo");
Thread.Sleep(1000);
Console.WriteLine("Woooorld");
}
}
If I run the code above, the following is printed:
Helloooo
Woooorld
You can see that I don't add a t.Join()
that's because t is a foreground thread. But if try to do the same with async the following happens:
class Program
{
public static void Main(string[] args)
{
Thread t = new Thread(Main2)
{ IsBackground = false };
t.Start();
}
// Can't use "public static async Task main2"
// because you need to pass in a void method to a new thread
public static async void Main2()
{
Console.WriteLine("Helloooo");
await Task.Delay(1000);
Console.WriteLine("Woooorld");
}
}
Only
Helloooo
Is printed, and the program exits, even though the new thread is a foreground thread. Now I understand what is happening here, When the new thread reaches await Task.Delay(1000);
It starts up a state machine and releases the thread for other things. What I want to know is what I have to change to let my original thread die, and let my new thread take over. I want to understand how the async/await chain gets started.