我是否应该担心“这种异步方法缺少 'await' 操作符并且将同步运行"?警告 [英] Should I worry about "This async method lacks 'await' operators and will run synchronously" warning
问题描述
我有一个公开一些异步方法的接口.更具体地说,它定义了返回 Task
或 Task
的方法.我正在使用 async/await 关键字.
I have a interface which exposes some async methods. More specifically it has methods defined which return either Task
or Task<T>
. I am using the async/await keywords.
我正在实现这个接口.但是,在其中一些方法中,此实现无需等待.出于这个原因,我收到编译器警告CS1998:此异步方法缺少 'await' 运算符,将同步运行......"
I am in the process of implementing this interface. However, in some of these methods this implementation doesn't have anything to await. For that reason I am getting the compiler warning "CS1998: This async method lacks 'await' operators and will run synchronously..."
我明白为什么我会收到这些警告,但我想知道在这种情况下我是否应该对它们做些什么.忽略编译器警告感觉不对.
I understand why I am getting these warnings but am wondering whether I should do anything about them in this context. It feels wrong to ignore compiler warnings.
我知道我可以通过等待 Task.Run
来修复它,但是对于只执行一些廉价操作的方法来说,这感觉是错误的.听起来它还会为执行增加不必要的开销,但我也不确定它是否已经存在,因为 async
关键字存在.
I know I can fix it by awaiting on Task.Run
but that feels wrong for a method that is only doing a few inexpensive operations. It also sounds like it will add unneeded overhead to the execution but then I am also not sure if that is already there because the async
keyword is present.
我应该忽略警告还是有办法解决我没有看到的问题?
Should I just ignore the warnings or is there a way of working around this that I am not seeing?
推荐答案
async 关键字只是一个方法的实现细节;它不是方法签名的一部分.如果一个特定的方法实现或覆盖没有什么可等待的,那么只需省略 async 关键字并使用 Task.FromResult
The async keyword is merely an implementation detail of a method; it isn't part of the method signature. If one particular method implementation or override has nothing to await, then just omit the async keyword and return a completed task using Task.FromResult<TResult>:
public Task<string> Foo() // public async Task<string> Foo()
{ // {
Baz(); // Baz();
return Task.FromResult("Hello"); // return "Hello";
} // }
如果您的方法返回 TaskTaskTask.FromResult(0)
似乎是一个流行的选择:
If your method returns Task instead of Task<TResult>, then you can return a completed task of any type and value. Task.FromResult(0)
seems to be a popular choice:
public Task Bar() // public async Task Bar()
{ // {
Baz(); // Baz();
return Task.FromResult(0); //
} // }
或者,从 .NET Framework 4.6 开始,您可以返回 Task.CompletedTask:
Or, as of .NET Framework 4.6, you can return Task.CompletedTask:
public Task Bar() // public async Task Bar()
{ // {
Baz(); // Baz();
return Task.CompletedTask; //
} // }
这篇关于我是否应该担心“这种异步方法缺少 'await' 操作符并且将同步运行"?警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!