It says here :
Async methods can have the following return types:
Task
, for an async method that performs an operation but returns no value.
Task <TResult>
, for an async method that returns a value.
void
, for an event handler.Starting with C# 7.0, any type that has an accessible
GetAwaiter
method . The object returned by theGetAwaiter
method must implement theSystem.Runtime.CompilerServices.ICriticalNotifyCompletion
interface.Starting with C# 8.0,
IAsyncEnumerable<T>
, for an async method that returns an async stream .
Question . How to understand the phrase: "Asynchronous methods can have the following return types: ... any type that has an accessible GetAwaiter
method" , if the actual is not?
This code is not working:
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();
}
}
The summary docs are a bit confusing. GetAwaiter
is insufficient to be used as a return type; GetAwaiter
is more about await
than async
.
The more detailed docs clarify:
In addition, the type returned from the GetAwaiter method must have the System.Runtime.CompilerServices.AsyncMethodBuilderAttribute attribute.
The AsyncMethodBuilder
attribute gives the compiler sufficient information to actually build and control the return type instance from the async state machine.
TaskAwaiter<T>
does not have this attribute. It doesn't normally need it because task return types are "grandfathered in" and treated specially by the compiler.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.