Why does the async keyword exist

最后都变了- 提交于 2019-11-27 01:15:40

It was introduced mainly to avoid backward compatibility issues. If the async-ness of a method must be inferred by the compiler (that would be through the detection of await keywords), then there are subtle scenarios where existing code would suddenly be treated differently, notably when you have identifiers (variable or function names called await).

A full explanation is here: http://blogs.msdn.com/b/ericlippert/archive/2010/11/11/whither-async.aspx

I think perhaps this article covers the reasoning:

http://blogs.msdn.com/b/ericlippert/archive/2010/11/11/whither-async.aspx

The first paragraph states:

A number of people have asked me what motivates the design decision to require any method that contains an "await" expression to be prefixed with the contextual keyword "async".

It concludes:

That's a whole lot of pros and cons; after evaluating all of them, and lots of playing around with the prototype compiler to see how it felt, the C# designers settled on requiring "async" on a method that contains an "await". I think that's a reasonable choice.

The short of it is backwards compatibility.

Further reading:

http://blogs.msdn.com/b/ericlippert/archive/2010/10/29/asynchronous-programming-in-c-5-0-part-two-whence-await.aspx

For me, the most compelling reason is that the meaning of the return statement changes when a function becomes async. Without asnyc return x means "return a task with the value x", and with async it means "set the result of the task to x.

I wrote up a summary of async/await keyword questions on my blog a while ago.

Here's the conclusion of the section "Inferring async":

Eric Lippert has the definitive post on the subject. It's also been discussed in blog comments, Channel9, and forums.

To summarize, a single-word await keyword would be too big of a breaking change. The choice was between a multi-word await (e.g., await for) or a keyword on the method (async) that would enable the await keyword just within that method. Explicitly marking methods async is easier for both humans and computers to parse, so they decided to go with the async/await pair.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!