Keywords

These keywords were added by machine and not by the authors. This process is experimental and the keywords may be updated as the learning algorithm improves.

An asynchronous method is a method that can return before it has finished executing. Any method that performs a potentially long running task, such as accessing a web resource or reading a file, can be made asynchronous to improve the responsiveness of the program. This is especially important in graphical applications, because any method that takes a long time to execute on the user interface thread will cause the program to be unresponsive while waiting for that method to complete.

Async and await

Introduced in C# 5.0, the async and await keywords allow asynchronous methods to be written with a simple structure that is similar to synchronous (regular) methods. The async modifier specifies that the method is asynchronous and that it can therefore contain one or more await expressions. An await expression consists of the await keyword followed by an awaitable method call.

async void MyAsync()

{

  System.Console.Write("A");

  await System.Threading.Tasks.Task.Delay(2000);

  System.Console.Write("C");

}

The method above will run synchronously until the await expression is reached, at which point the method is suspended and execution returns to the caller. The awaited task is scheduled to run in the background on the same thread. In this case the task is a timed delay that will complete after 2000 milliseconds. Once the task is complete the remainder of the async method will execute.

Calling the async method from Main will output “AB” followed by “C” after the delay. Note the use of the ReadKey method here to prevent the console program from exiting before the async method has finished.

static void Main()

{

  new MyApp().MyAsync();

  System.Console.Write("B");

  System.Console.ReadKey();

}

Async return types

An async method can have one of three built-in return types: Task<T>, Task, and void. Specifying Task or void denotes that the method does not return a value, whereas Task<T> means it will return a value of type T. In contrast to void, the Task and Task<T> types are awaitable, so a caller can use the await keyword to suspend itself until after the task has finished. The void type is mainly used to define async event handlers, as event handlers require a void return type.

Custom async methods

In order to call a method asynchronously it has to be wrapped in another method that returns a started task. To illustrate, the following method defines, starts and returns a task which takes 2000 milliseconds to execute before it returns the letter “Y”. The task is here defined through the use of a lambda expression for conciseness.

using System.Threading.Tasks;

using System.Threading;

// ...

Task<string> MyTask()

{

  return Task.Run<string>( () => {

    Thread.Sleep(2000);

    return "Y";

  });

}

This task method can be called asynchronously from an async method. The naming convention for these methods is to append “Async” to the method name. The asynchronous method in this example awaits the result of the task and then prints it.

async void MyTaskAsync()

{

  string result = await MyTask();

  System.Console.Write(result);

}

The async method is called in the same way as a regular method, as can be seen in the following Main method. The output of the program will be “XY”.

static void Main()

{

  new MyApp().MyTaskAsync();

  System.Console.Write("X");

  System.Console.ReadKey();

}