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 multithreading 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 multithreaded code. This coincided with the common availability of multithread/multicore 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, PLINQ, which is covered in Recipe 4.10, shipped in the same time frame. TPL is still an important part of the developer’s toolkit for in-process CPU-intensive multithreading.

Building on the concepts of Task, from TPL, Microsoft introduced 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 simplified this by introducing the async/await keywords and making the code and its order of execution very similar to synchronous code. In addition to simplification, a primary use case for C# async is out-of-process communication, as opposed to where TPL shines for in-process CPU intensive ...

Get C# Cookbook now with the O’Reilly learning platform.

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