5 Async-await and multithreading
This chapter covers
- Using async-await and multithreading together
- Running code after an await
- Using locks with async-await
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.
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.
5.1 Asynchronous programming and multithreading
To demonstrate the interaction between asynchronous programing and multithreading we’ll start with a method that reads 10 files in parallel, using asynchronous operations, and then wait for all the read operations to complete, and, just for the fun of it, we won’t make the method itself async, just use asynchronous operations inside it:
Listing 5.1 Read 10 files
public void Read10Files()
{
var tasks = new Task[10];
for(int i=0;i<10;++i)
{
tasks[i] = File.ReadAllBytesAsync($"{i}.txt");
}
Task.WaitAll(tasks);
}