c# - 如何在接口(interface)中的方法上使用 await

标签 c# .net-4.5 async-await

当使用 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/

相关文章:

javascript - 调用时间过长后, promise 链会重复自身

c# - 需要使用 Linq 将列表转换为不同列表的帮助

c# - 为 Web 应用程序创建合理文件大小的缩略图

c# - 反 xsrf token 验证失败

javascript - Jest + NodeJS 中的 super 测试,异步/等待

javascript - 等待事件发生时返回 promise 的函数

c# - 使用嵌入式 Mono (libmono-2.0) 时 C# 对象何时被垃圾回收

c# - 如何将 ViewModel 属性作为模型传递给局部 View ?

c# - Thread.CurrentPrincipal 已通过身份验证,但 ClaimsPrincipal.Current 未通过身份验证

asp.net-mvc-4 - 子操作输出缓存与 FIPS 不兼容吗?