Asynchronous Methods

Learn to write clean asynchronous code using the async modifier and await operator to handle non-blocking operations and return values.

In previous lessons, we used Task.Run and ContinueWith or manual waiting to manage background operations. While powerful, this approach can lead to messy, nested code known as “callback hell”.

To solve this, C# provides two keywords: async and await. These allow you to write asynchronous code that looks and behaves like synchronous code (top-to-bottom execution) while remaining non-blocking.

Creating async methods

An asynchronous method is a method that can suspend its execution without blocking the thread it is running on. Defining an asynchronous method requires three elements:

  1. Modifier: Use the async modifier in the method signature.

  2. Return type: Return Task instead of void or Task<T> instead of T.

  3. Await: Use the await keyword inside the body at least once.

Naming convention: It is standard practice to append the suffix Async to the names of asynchronous methods, such as DownloadFileAsync or CalculateAsync.

The await operator

The await operator coordinates the execution flow. When execution encounters await task:

  1. It verifies task completion.

  2. If incomplete, it yields control to the caller and frees the thread for other work.

  3. When the task eventually finishes, the method resumes execution right where it left off.

We will now convert a blocking method into an asynchronous one.