使用和不使用异步的任务 return 类型

Task return type with and without Async

我对 async 关键字的行为有点困惑。

假设我有两种方法,

public async Task DoSomething1()
{
    await Task.Run(() =>
    {
        for(int i = 0; i<3; i++)
        {
            Console.WriteLine("I m doing something:" + i);
        }
    });
}

public Task DoSomething2()
{
    return Task.Run(() =>
    {
        for(int i = 0; i<3; i++)
        {
            Console.WriteLine("I m doing something:" + i);
        }
    });
}

根据我的理解,这两种方法都是可以等待的。但是,当我编写一个具有 Task return 类型但没有 async 关键字的方法时,我需要 return 一个 Task 否则编译器会生成错误。一个方法应该 return 它的类型是很常见的事情。但是当我将它与 async 关键字一起使用时,编译器会生成另一个错误,您不能 return a Task。那是什么意思呢?我在这里完全糊涂了。

如果您在代码中使用 await,则需要在方法中使用 async 关键字。

如果您使用 async 并想要 return 一个实际类型,您可以 return 将类型作为通用任务 Task<int>

以下是 async 方法的有效 return 类型:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/async-return-types

  1. Task<TResult>,对于 return 是一个值的异步方法。
  2. Task,用于执行操作但 return 没有值的异步方法。
  3. void,用于事件处理程序。

(...) “async”. This keyword allows that inside the method the word “await” can be used, and modifies how its result is handled by the method. That’s it.

The method runs synchronously until it finds the word “await” and that word is the one that takes care of asynchrony. “Await” is an operator that receives a parameter: an awaitable (an asynchronous operation) behaves in this way:

来自here