How to use async and await in C#?

In C#, async and await are keywords used for handling asynchronous operations.

The async keyword is used to declare a method as asynchronous, allowing it to pause during execution and allowing other code to continue while waiting for the asynchronous operation to complete.

The await keyword is used to wait for the completion of an asynchronous operation and return the result of the asynchronous operation. It can only be used in asynchronous methods and can only wait for methods that return a task, task result, awaitable object (such as ValueTask), or custom asynchronous operation type.

The basic steps of using async and await are as follows:

  1. Add the keyword async before the return type in a method declaration to indicate that the method is asynchronous.
  2. Use the await keyword in places where you need to wait for asynchronous operations to complete.
  3. The expression modified by the ‘await’ keyword must be a method call that returns a task type, so that the method’s execution can be paused and resumed when the asynchronous operation is completed.
  4. By using the await keyword to wait for the completion of asynchronous operations, you can obtain the result of the asynchronous operation and continue executing the subsequent code.

Here is an example using async and await:

public async Task<string> GetDataAsync()
{
    // 异步操作,例如从网络获取数据
    string result = await DownloadDataAsync();

    // 在异步操作完成后继续执行后续的代码
    Console.WriteLine("异步操作完成");

    return result;
}

In the above example, the GetDataAsync method is an asynchronous method that uses the await keyword to wait for the completion of the DownloadDataAsync method. After the DownloadDataAsync method is completed, the returned result is stored in the result variable, and the subsequent code is then executed.

Please note that the types returned by asynchronous methods are typically Task (for void returns) or Task (for non-void returns), in order to allow the caller to await the completion of the asynchronous operation. In the example above, the GetDataAsync method returns a Task type task.

bannerAds