6 When to use async/await

 

This chapter covers

  • The importance of async/await
  • The disadvantages of async/await
  • Deciding when to use async/await and when to avoid it

You probably 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 know. However, it’s important to acknowledge that they are not suitable for every situation, and if used inappropriately, they will make your software more complicated and create some bugs that are really difficult to find.

This chapter talks about the performance gains of multithreading and asynchronous programming, as well as how asynchronous programming can backfire sometimes and make our life miserable. For the rest of this chapter, I’m going to talk about the concept of asynchronous programming and the C# feature of async/await as if they were interchangeable—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 truly 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

Summary