How do you create an asynchronous method in C#?

后端 未结 3 670
清酒与你
清酒与你 2020-11-30 16:10

Every blog post I\'ve read tells you how to consume an asynchronous method in C#, but for some odd reason never explain how to build your own asynchronous methods to consume

3条回答
  •  臣服心动
    2020-11-30 17:00

    I don't recommend StartNew unless you need that level of complexity.

    If your async method is dependent on other async methods, the easiest approach is to use the async keyword:

    private static async Task CountToAsync(int num = 10)
    {
      for (int i = 0; i < num; i++)
      {
        await Task.Delay(TimeSpan.FromSeconds(1));
      }
    
      return DateTime.Now;
    }
    

    If your async method is doing CPU work, you should use Task.Run:

    private static async Task CountToAsync(int num = 10)
    {
      await Task.Run(() => ...);
      return DateTime.Now;
    }
    

    You may find my async/await intro helpful.

提交回复
热议问题