Chapter 5. What await Actually Does

There are two ways to think about the async feature of C# 5.0, and in particular what happens at an await keyword:

  • As a language feature, which has a defined behavior that you can learn

  • As a compile-time transformation, that is syntactic sugar for a more complex piece of C# that doesn’t use async

Both are completely true; they are two sides of the same coin. In this chapter, we will concentrate on the first way of looking at async. In Chapter 14, we’ll look at it from the other point of view, which is more complex but provides some details that will make debugging and performance considerations more clear.

Hibernating and Resuming a Method

When the execution of your program reaches an await keyword, we want two things to happen:

  • The current thread executing your code should be released to make your code asynchronous. That means from a normal, synchronous, point of view, your method should return.

  • When the Task that you awaited is complete, your method should continue from where it used to be, as if it hadn’t returned earlier.

To achieve this behavior, your method must pause when it reaches an await, and then resume at a later point.

I think of this process as a small scale version of when you hibernate a computer (S4 sleep). The current state of the method is stored away, and the method exits completely. When a computer hibernates, the dynamic, running state of the computer is saved to disk, and it turns completely off. Just as you can unplug the power ...

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.