chapter six

6 When to use async-await

 

This chapter covers

  • The importance of async-await
  • The disadvantages of async-await.
  • Deciding in which conditions to use async-await and in which conditions to avoid it.

I believe you won’t find it surprising that I, the author of a book about multithreading and asynchronous programming, think that they are important, useful, and something that every software developer should definitely know. However, it’s important to acknowledge that it is not appropriate for every situation – and if used inappropriately they will make your software more complicated and create some really difficult to find bugs.

In this chapter, we’re going to talk about the performance gains of multithreading and asynchronous programming – and then we’re going to talk about some of the ways using asynchronous programming can backfire and make our life miserable.

For the rest of this chapter, I’m going to talk about the concept of asynchronous programming and about the C# feature of async-await almost interchangeably - because while they are different, async-await is by far the easiest way to do asynchronous programming in C#. If you want to use asynchronous programming in C# you should use async-await, and conversely, if you don’t use asynchronous programming, you will find async-await mostly useless.

First, let’s quickly go over the scenarios where async-await really shines.

6.1 Asynchronous benefits on servers

6.2 Asynchronous benefits on native client applications

6.3 The downside of async-await

6.3.1 Asynchronous programming is contagious

6.3.2 Asynchronous programming has more edge cases

6.3.3 Multithreading has even more edge cases

6.3.4 Async-await is expensive

6.4 When to use async await

6.5 Summary