What is the reason behind CS1998 “method lacks await operators”

前端 未结 1 842
被撕碎了的回忆
被撕碎了的回忆 2021-01-02 07:23

The C# compiler generates a CS1998 warning when an async method lacks any await operators.

What are the reasons behind the warning?

相关标签:
1条回答
  • 2021-01-02 08:00

    What are the reasons behind the warning?

    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.

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题