The asynchronous entry point is just a compiler trick. Behind the scenes, the compiler generates this real entry point:
private static void <Main>(string[] args)
{
_Main(args).GetAwaiter().GetResult();
}
If you change your code to be like this:
class Program
{
private static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
static async Task MainAsync(string[] args)
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
string message = await DoWorkAsync();
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(message);
}
static async Task<string> DoWorkAsync()
{
await Task.Delay(3_000);
return "Done with work!";
}
}
You'll get this:
1
4
Done with work!
1
As expected, the main thread is waiting for the work to be done.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…