Part 5. C# 5: Asynchrony made simple

 

It’s simple to describe C# 5: it has exactly one big feature (asynchronous functions) and two tiny ones.

Chapter 15 is all about asynchrony. The aim of the asynchronous functions feature (often just called async/await for short) is to make asynchronous programming easy...or at least easier than it was before. It doesn’t try to remove the inherent complexity of asynchrony; you still need to consider the consequences of operations completing in an unexpected order, or the user pressing another button before the first operation has completed, but it removes a lot of the incidental complexity. This allows you to see the wood for the trees, and build robust, readable solutions to those inherent complexities.

In the past, asynchronous code has often turned into spaghetti, with the logical execution path jumping from method to method as one asynchronous call completes and starts another one. With asynchronous functions, you can write code that looks synchronous, with familiar control structures such as loops and try/catch/finally blocks, but with an asynchronous execution flow triggered by a new contextual keyword (await). The difference in readability is simply staggering, in my experience. We’ll go into a lot of depth on this topic, not just in terms of how the language behaves, but how it’s implemented by the Microsoft C# compiler.