Chapter 6. Programming Asynchronously

It used to be that most of the code anyone wrote was synchronous. Things like concurrency, thread pools, and parallel programming were the domain of specialized experts who sometimes still got it wrong. Historical Internet forums, UseNet, and even books were full of warnings to not try multi-threading unless you know what you’re doing and have a strong requirement for it. However, that’s changed.

In 2010, Microsoft introduced the Task Parallel Library (TPL), which made it a lot easier to write multi-threaded code. This coincided with the common availability of multi-thread/core CPU architectures. One of the TPL primitives was the Task class, which represented a promise to perform some work, on a separate thread, and return the results. Interestingly, Parallel LINQ (PLINQ), which is covered in Recipe 4.10, shipped in the same timeframe. TPL is still an important part of the developer’s toolkit for in-process CPU intensive multi-threading.

Building on the concepts of Task, from TPL, Microsoft introduced Asynchronous Programming (async) via specialized language syntax in C# 4. While we had asynchronous programming since C# 1, through delegates, it was more complex and less efficient. In C# 5, async ...

Get C# Cookbook now with O’Reilly online learning.

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