Chapter 8. Which Thread Runs My Code?

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.

Before the First await

In each async method you write, some code will be before the first occurrence of the await keyword. Equally, some code is in the expression that gets awaited.

This code always runs in the calling thread. Nothing interesting happens before the first await.

Note

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 purpose.

In the case of a UI application, that means the code before the first await runs in the UI thread. Likewise, in an ASP.NET web application, it runs in an ASP.NET worker thread.

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 puppet Task. That method is the source of the asynchrony ...

Get Async in C# 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.