user19747379
user19747379

Reputation:

An async method cannot return any type that has an accessible GetAwaiter method

It says here:

Async methods can have the following return types:

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

Answers (1)

Stephen Cleary
Stephen Cleary

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

Related Questions