How to use asynchronous waiting methods in C#?

In C#, you can use the async and await keywords to implement asynchronous waiting methods.

Firstly, it is necessary to declare the method as an asynchronous method by adding the async keyword before the method signature. Then, you can use the await keyword to wait for an asynchronous task to complete.

Here is a sample code demonstrating how to use async and await to asynchronously wait for a method to complete:

using System;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine("Start");

        // 调用异步方法并等待它完成
        await LongRunningTask();

        Console.WriteLine("End");
    }

    public static async Task LongRunningTask()
    {
        Console.WriteLine("Long running task started");

        // 模拟一个耗时的操作
        await Task.Delay(2000);

        Console.WriteLine("Long running task completed");
    }
}

In the example above, the Main method is marked as an asynchronous method, using the await keyword to wait for the completion of the LongRunningTask method. The LongRunningTask method is also marked as an asynchronous method, simulating a time-consuming operation using await Task.Delay(2000).

bannerAds