Reputation:
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();
}
}
Upvotes: 3
Views: 232
Reputation: 457402
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.
Upvotes: 4