考虑:
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
C c = new C();
c.FooAsync(); // warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
((I)c).FooAsync(); // No warning
}
}
class C : I
{
public async Task FooAsync()
{
}
}
interface I
{
Task FooAsync();
}
Run Code Online (Sandbox Code Playgroud)
如果我直接在c对象上调用async方法,我会收到编译器警告.这里可能有一个错误,所以我很高兴发出警告.
但是,如果我在接口方法上进行相同的调用,则不会收到警告.在这段代码中让一个错误过去很容易.
我如何确保不犯这个错误?我可以申请保护自己的模式吗?
主要不是异步,所以不能使用await.这似乎略微混淆了编译器消息.如果将调用放入实际的异步方法中;
static void Main(string[] args)
{
Task.Run(async () =>
{
C c = new C();
c.FooAsync();
((I) c).FooAsync();
});
}
Run Code Online (Sandbox Code Playgroud)
......两人都会警告.
第10行:由于未等待此调用,因此在完成调用之前,将继续执行当前方法.考虑将'await'运算符应用于调用的结果.
第11行:由于未等待此调用,因此在完成调用之前,将继续执行当前方法.考虑将'await'运算符应用于调用的结果.
编辑:似乎所有返回Task 异步方法的方法都会发出警告,除非你等待或分配它们; 请注意,我们正在使用甚至没有提到异步的接口;
interface I
{
Task FooAsync();
}
static void Main(string[] args)
{
I i = null;
i.FooAsync(); // Does not warn
// await i.FooAsync(); // Can't await in a non async method
var t1 = i.FooAsync(); // Does not warn
Task.Run(async () =>
{
i.FooAsync(); // Warns CS4014
await i.FooAsync(); // Does not warn
var t2 = i.FooAsync(); // Does not warn
});
}
Run Code Online (Sandbox Code Playgroud)