当使用 await 关键字针对一个接口(interface)(由于模拟、远程处理或类似的)实现时,并且具有一个带有返回 Task<> 的方法的接口(interface):
interface IFoo
{
Task<BigInteger> CalculateFaculty(int value);
}
编译器出现错误:
The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'
考虑到返回类型是“任务”,这有点不寻常。这个问题有点令人沮丧,并迫使我使用 continuation 样式 或围绕此接口(interface)提供额外的代理(因此对于几乎每个对我来说都不可行的接口(interface))
有没有人知道如何解决这个问题?
最佳答案
消息不是关于接口(interface)的,而是关于调用方法的。您需要使用 async
修饰符标记包含 await
关键字的方法:
public interface IFoo
{
Task<int> AwaitableMethod();
}
class Bar
{
static async Task AsyncMethod() // marked as async!
{
IFoo x;
await x.AwaitableMethod();
}
}
关于c# - 如何在接口(interface)中的方法上使用 await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12581764/