CS1998“缺乏等待操作员的方法"背后的原因是什么? [英] What is the reason behind CS1998 "method lacks await operators"
问题描述
当async
方法缺少任何await
运算符时,C#编译器会生成CS1998警告.
The C# compiler generates a CS1998 warning when an async
method lacks any await
operators.
警告背后的原因是什么?
我知道async
通过添加状态机和异常处理而在方法中带来了开销.
I know that async
introduces overhead in the method by adding a statemachine and exception handling.
警告性能的主要原因是什么?
还是通知我可能在某处忘记了await
的原因?
Is the primary reason for the warning performance?
Or is the reason to notify me that I might have forgotten an await
somewhere?
也许语言设计团队的某人可以对此有所了解...:)
Maybe someone from the language design team can shed some light on this one... :)
(请:请勿发布您可以删除async
来使警告消失的答案".我想知道警告的原因和决定,而不是解决该警告的方法.)
(Please: do not post answers that say 'you can remove async
to make the warning go away'. I want to know the reasons and decisions behind the warning, not ways to work around it.)
推荐答案
警告背后的原因是什么?
What are the reasons behind the warning?
简单地说,不使用await
的async
方法几乎肯定是错误的.并非总是错误,否则将是一个错误.但是几乎总是错误的,因此发出警告.
Simply put, an async
method that does not use await
is almost certainly wrong. Not always wrong, or this would be an error. But almost always wrong, hence the warning.
一个非常常见的异步新手错误是假设async
的意思是使此方法异步".这通常与异步"意味着在后台线程上运行"的假设配对,但有时只是魔术"的假设.
An incredibly common async-newbie mistake is to assume async
means "make this method asynchronous". This is commonly paired with the assumption that "asynchronous" means "run on a background thread", but sometimes it's just an assumption of "magic".
因此,警告明确指出代码将同步运行.
Thus, the warning explicitly points out that the code will run synchronously.
我还发现该警告在重构自己的代码时很有用-有时我会遇到async
方法,该方法应更改为同步方法,并且此警告指出了这一点.
I have also found this warning helpful when refactoring my own code - sometimes I end up with an async
method that should be changed to a synchronous method, and this warning points that out.
的确,如果您具有非平凡(即,可能产生异常的)同步代码并且需要实现异步方法签名,则不带await
的async
对于减少代码很有用.在这种情况下,可以使用async
避免使用六行TaskCompletionSource<T>
和try
/catch
代码.但是,这是一个非常小的用例.在绝大多数情况下,警告是有帮助的.
It's true that async
without await
could be useful to reduce code if you have non-trivial (i.e., possibly exception-generating) synchronous code and you need to implement an asynchronous method signature. In that case, you can use async
to avoid a half-dozen lines of TaskCompletionSource<T>
and try
/catch
code. But this is an extremely small use case; the vast majority of the time, the warning is helpful.
这篇关于CS1998“缺乏等待操作员的方法"背后的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!