I’m trying to understand how async/await works in C#, specifically related to the thread behavior. I’ve been reading Stephen Cleary’s blog post on async and await (https://blog.stephencleary.com/2012/02/async-and-await.html), and one part of the documentation confuses me:
The beginning of an async method is executed just like any other
method. That is, it runs synchronously until it hits an “await” (or
throws an exception).
I have the following code:
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine($"Thread Id entering Main Method: {Thread.CurrentThread.ManagedThreadId}");
await Something_One();
}
static async Task Something_One()
{
Console.WriteLine($"Thread Id entering Something_One: {Thread.CurrentThread.ManagedThreadId}");
await Something_Two();
}
static async Task Something_Two()
{
Console.WriteLine($"Thread Id Entring Something_Two: {Thread.CurrentThread.ManagedThreadId}");
await Task.Delay(1000);
}
}
The output I’m seeing is:
Thread Id entering Main Method: 1
Thread Id entering Something_One: 1
Thread Id Entring Something_Two: 1
According to the documentation, I expected the synchronous execution to stop at the first await keyword encountered(and maybe continue on another thread), which is await Something_Two() in the Something_One method. However, the output shows that Something_Two also executes synchronously until it hits the await Task.Delay(1000) line.
Why does Something_Two execute synchronously even though it’s called from an await expression in Something_One?
I’m trying to understand the rationale behind the thread behavior I’m observing, especially in light of the documentation statement that async methods run synchronously until they hit an await. Could someone please explain what’s happening under the hood