Saving Evaluation State with Stack Spilling

Because the new await keyword is used in an expression context, some complexity applies to maintaining the evaluation stack across the initiation of the asynchronous operation and its completion. The technique used to make this work is called stack spilling.

To understand this complexity and how to deal with it, consider the following example of an asynchronous method:

async Task<int> Demo(){    return Bar() + (Foo() + (Qux() + await Baz()));}

In this piece of code, we call four methods as part of one big expression. Of those four methods, the first three simply return an int. The Baz method, however, returns a Task<int> that will be awaited.

Notice the use of parentheses ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.