Why does the async keyword exist
Browsing through the channel 9 msdn videos I found the following unanswered comment and was hoping someone could possibly explain it?
I dont get the point of the async keyword. Why not just allow the await keyword anytime the method returns Task, just like iterators can yield return on any method that returns an IEnumerable.
I'm sure there is a good reason, I'd just like to understand why the above suggestion was not possible.
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
.
上一篇: 异步/等待高性能服务器应用程序?
下一篇: 为什么存在async关键字