Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

c# - 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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...