As I’ve said before, asynchronous programming is all about threads. In C#, that means we need to understand which .NET thread is running our code at what points in the program, and what happens to the threads while long-running operations take place.
In each async method you write, some code will be before the first
occurrence of the
Equally, some code is in the expression that gets awaited.
This code always runs in the calling thread. Nothing interesting
happens before the first
This is one of the most common misconceptions about async. Async
never schedules your method to run on a background thread. The only way
to do that is using something like
Task.Run, which is explicitly for that
In the case of a UI application, that means the code before the
await runs in the UI thread.
Likewise, in an ASP.NET web application, it runs in an ASP.NET worker
Typically, you might run another async method as the expression
being awaited on the line containing the first
await. Because this expression is executed
before the first
await, it must also
get run in the calling thread. That means the calling thread will continue
executing code deep into your application, all the way until some method
actually returns a
Task. The method
that does that might be a framework method, or it might be a method using
TaskCompletionSource to construct a
Task. That method is the source of the asynchrony ...