Tho*_*man 29 c# async-await .net-4.5
当使用await关键字并且具有返回Task <>的方法的接口实现针对接口(因为模拟,远程处理或类似)时:
interface IFoo
{
Task<BigInteger> CalculateFaculty(int value);
}
Run Code Online (Sandbox Code Playgroud)
编译器出现错误:
'await'运算符只能在异步方法中使用.考虑使用'async'修饰符标记此方法并将其返回类型更改为'Task'
考虑到返回类型是"任务",这有点不寻常.这个问题有点令人沮丧,并迫使我使用延续风格 "退回" 或在此界面周围提供额外的代理(因此对于几乎所有对我来说都不可行的界面)
有没有人对如何解决这个问题有个好主意?
jer*_*enh 30
该消息不是关于接口,而是关于调用方法.您需要await使用async修饰符标记包含关键字的方法:
public interface IFoo
{
Task<int> AwaitableMethod();
}
class Bar
{
static async Task AsyncMethod() // marked as async!
{
IFoo x;
await x.AwaitableMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
Ant*_*kov 12
这一定是好的:
interface IFoo
{
Task<BigInteger> CalculateFaculty(int value);
}
public class Foo: IFoo
{
public async Task<BigInteger> CalculateFaculty(int value)
{
var res = await AsyncCall();
return res;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
public async Task DoSomething(IFoo foo)
{
var result = await foo.CalculateFaculty(123);
}
Run Code Online (Sandbox Code Playgroud)