Asynchronous Methods
Learn to write clean asynchronous code using the async modifier and await operator to handle non-blocking operations and return values.
We'll cover the following...
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:
Modifier: Use the
asyncmodifier in the method signature.Return type: Return
Taskinstead ofvoidorTask<T>instead ofT.Await: Use the
awaitkeyword 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:
It verifies task completion.
If incomplete, it yields control to the caller and frees the thread for other work.
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.