简体   繁体   中英

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();
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM