Member-only story
Where is the magic thread in asynchronous code?
Since I wrote my last blog post regarding the asynchronous state machine (https://stefansch.medium.com/what-the-async-keyword-actually-does-bb10d54ce31c), I felt like I really missed bringing a point across, which caused me quite some confusion when working with async code, until it finally clicked.
Where’s the magic thread?
For a lot of people who initially learned about concurrency and simultaneous execution in the context of parallel execution through threading, the first few contact points with asynchronous concurrent programming can be a bit weird. Usually one question comes up:
“With all these requests executing at the same time, someone has to actually do them, right? Where’s that magical thread keeping all of this synchronized?”
Short answer: Nowhere. There is no magic thread waiting for asynchronous operation. Granted, that might have been very simplified.
Let’s take an example at hand to see what is going on here.
async Task Main()
{
var httpClient = new HttpClient();
var result = await httpClient.GetStringAsync("https://medium.com");
Console.WriteLine(result);
}
This code should be straightforward, but still, a lot of programmers have trouble understanding what exactly…