Asynchronous Methods

Create methods that can run asynchronously.

Introduction

We’ve seen how to perform some actions asynchronously using the Task class. Asynchronous execution allows us to delegate some parts of our program to background pool threads. If we have a method that has some asynchronous code inside, how can we inform its users that it’s asynchronous? How can others call this method asynchronously without encapsulating it inside a Task instance? Consider the following example:

public void Print()
{
	string message = "Asynchronous code inside!";
	
	// This part of the method runs asynchronously 
	Task.Run(() => Console.WriteLine(message));
}

The Print() method includes a part that runs asynchronously in the background. If we were to call the Print() method, however, the current thread will be blocked until the method is done executing. We can’t call it asynchronously unless we encapsulate the method inside another Task instance**:

Task.Run(() => Print());

Also, without looking at the method’s source code, we don’t know if there’s asynchronous code inside. Fortunately, there’s a much cleaner approach to creating and calling asynchronous methods in .NET apps using the async and await operators.

Create async methods

An asynchronous method is a method that can be called without blocking the current thread. In terms of syntax, an asynchronous method is the one that

  1. Has the async modifier.
  2. Has one or several await statements inside its body.
  3. Returns either void, Task, or its derivatives.

Asynchronous methods also can’t have parameters modified with ref or out keywords**.

It’s good practice to name asynchronous methods with Async at the end (PrintAsync()).

Having the async modifier doesn’t make a method asynchronous by itself, however. It’s the developer’s responsibility to write asynchronous code inside the method. Let’s make our Print() method asynchronous:

Get hands-on with 1200+ tech skills courses.