gpt4 book ai didi

c# - 异步方法不能返回任何具有可访问的 GetAwaiter 方法的类型

转载 作者:行者123 更新时间:2023-12-05 02:26:58 26 4
gpt4 key购买 nike

它说 here :

Async methods can have the following return types:

问题。如何理解这句话:“异步方法可以具有以下返回类型:...任何具有可访问的 GetAwaiter 方法的类型”,如果实际不是?

此代码无效:

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

最佳答案

摘要文档有点困惑。 GetAwaiter不足以用作返回类型; GetAwaiter更多关于 awaitasync .

more detailed docs澄清:

In addition, the type returned from the GetAwaiter method must have the System.Runtime.CompilerServices.AsyncMethodBuilderAttribute attribute.

AsyncMethodBuilder属性为编译器提供了足够的信息来实际构建和控制异步状态机的返回类型实例。

TaskAwaiter<T> does not have这个属性。它通常不需要它,因为任务返回类型是“祖父”并且由编译器特殊处理。

关于c# - 异步方法不能返回任何具有可访问的 GetAwaiter 方法的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73439341/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com