chapter five

5 Async-await and multithreading

 

This chapter covers

  • Using async-await and multithreading together
  • Running code after an await
  • Using locks with async-await

In chapter 3 we talked about async-await but didn’t mention threads, especially we ignored where the callback passed to ContinueWith runs. In chapter 4 we talked about multithreading and almost didn’t mention async-await at all. In this chapter, we’ll connect those two together.

If you have read, heard, or seen anything about async-await, it was always explained in connection to multithreading; even the book you are reading right now combines asynchronous programming and multithreading. This is because asynchronous operations and multithreading work very well together and are often used together.

5.1 Asynchronous programming and multithreading

Asynchronous programming is about doing stuff that doesn’t require the CPU (like reading a file or waiting for data to arrive over the network) in the background while using the CPU to do something else. Multithreading is about doing stuff that may or may not require the CPU in the background while using the CPU to do something else. Those two things are obviously similar, and we use the same tools to interact with them.

For example, let’s write a method that reads 10 files in parallel, using asynchronous operations, and then wait for all the read operations to finish, and, just for the fun of it, don’t make the method itself async, just use asynchronous operations inside it:

5.2 Where does code run after await?

5.3 Locks and async/await

5.4 UI threads

5.5 Summary