It says here https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/async-return-types:
异步方法可以具有以下返回类型:
-
Task https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task,对于执行操作但不返回任何内容的异步方法
价值。
-
Task <TResult> https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1,对于返回值的异步方法。
-
void
,对于事件处理程序。
-
从 C# 7.0 开始,任何具有可访问性的类型GetAwaiter
method。返回的对象GetAwaiter
方法必须实现
这System.Runtime.CompilerServices.ICriticalNotifyCompletion https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.icriticalnotifycompletion界面。
-
从 C# 8.0 开始,IAsyncEnumerable<T> https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.iasyncenumerable-1,对于一个异步方法
返回一个异步流.
Question。如何理解这句话:“异步方法可以具有以下返回类型:...具有可访问的任何类型GetAwaiter
method",如果实际不是呢?
此代码不起作用:
using System.Runtime.CompilerServices;
async A Method() //Error CS1983 The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T>
{
await new A();
}
class A
{
public TaskAwaiter GetAwaiter()
{
return new TaskAwaiter();
}
}
摘要文档有点令人困惑。GetAwaiter
不足以用作返回类型;GetAwaiter
更多的是关于await
than async
.
The 更详细的文档 https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/async-return-types?WT.mc_id=DT-MVP-5000058#generalized-async-return-types-and-valuetasktresult阐明:
此外,从 GetAwaiter 方法返回的类型必须具有 System.Runtime.CompilerServices.AsyncMethodBuilderAttribute 属性。
The AsyncMethodBuilder
属性为编译器提供了足够的信息来实际构建和控制异步状态机的返回类型实例。
TaskAwaiter<T>
不具有 https://github.com/dotnet/corert/blob/c6af4cfc8b625851b91823d9be746c4f7abdc667/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs#L54这个属性。它通常不需要它,因为任务返回类型是“祖父”并由编译器特殊处理的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)