Control Flow in Asynchronous Methods

The beauty of await expressions is they’re like any other expression, hence they can appear almost everywhere in the body of asynchronous methods. Only a few places are not allowed to contain await expressions, including a lock statement, inside a finally block, and in an unsafe code context. Other than that, possibilities are almost endless.

In particular, the use of await expressions deep inside control flow logic is what makes the asynchronous programming features really powerful. For example, it’s possible to write an ordinary loop construct, with an await expression occurring in the middle of an iteration:

async Task<List<string>> DownloadSitesAsync(params string[] uris) ...

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.