Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason behind CS1998 "method lacks await operators"

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

What are the reasons behind the warning?

I know that async introduces overhead in the method by adding a statemachine and exception handling.

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... :)

(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.)

like image 686
cpt. jazz Avatar asked Jun 02 '16 14:06

cpt. jazz


People also ask

What happens when you call async method without await?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

Why there is no async await in Java?

The short answer is that the designers of Java try to eliminate the need for asynchronous methods instead of facilitating their use.

Can I use await for synchronous method?

Consider using the 'await' operator to await non-blocking API calls, or 'await Task. Run(...)' to do CPU-bound work on a background thread. SynchronousAsync. The calling code will still be able to await this method, but since the task returned by the Task.


1 Answers

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.

like image 96
Stephen Cleary Avatar answered Oct 21 '22 04:10

Stephen Cleary