How Asynchronous Methods Execute

Because await expressions are just expressions, you can use them in (almost) all places where you can use expressions. For example, it’s perfectly fine to write the following:

string res = await Bar(await Foo() + await Qux(), 42 * await Baz());

This code evaluates as if you had written the following:

var __t1 = Foo();var __t2 = await __t1;var __t3 = Qux();var __t4 = await __t3;var __t5 = __t2 + __t4;var __t6 = Baz();var __t7 = await __t5;var __t8 = 42 * __t7;var __t9 = Bar(__t5, __t8);string res = await __t9;

In this example, the containing asynchronous method can be suspended on no less than four occasions, corresponding to each of the await expressions. However, the code still executes sequentially with a top-to-bottom ...

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.