Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

It says here:

Async methods can have the following return types:

Task, for an async method that performs an operation but returns no
value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Task, 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 the GetAwaiter method must implement
the System.Runtime.CompilerServices.ICriticalNotifyCompletion
interface.

Starting with C# 8.0, IAsyncEnumerable, 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();
    }
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading