为什么存在 async 关键字
浏览 msdn 9 频道视频时,我发现以下未答复的评论,希望有人能解释一下?
我不明白 async 关键字的意义。为什么不直接允许 任何时候方法返回任务时都会使用await关键字,就像迭代器一样 可以在任何返回 IEnumerable 的方法上产生返回。
我确信有一个很好的理由,我只是想了解为什么上述建议不可能。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
引入它主要是为了避免向后兼容性问题。如果编译器必须推断方法的异步性(这将通过检测await关键字),那么在某些微妙的情况下,现有代码会突然被区别对待,特别是当您有标识符(称为
await
的变量或函数名称)时。完整的解释在这里: https://learn.microsoft.com/en-us/archive/blogs/ericlippert/asynchrony-in-c-5-part-6-whither-async
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 ofawait
keywords), then there are subtle scenarios where existing code would suddenly be treated differently, notably when you have identifiers (variable or function names calledawait
).A full explanation is here: https://learn.microsoft.com/en-us/archive/blogs/ericlippert/asynchrony-in-c-5-part-six-whither-async
我认为也许这篇文章涵盖了推理:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/asynchrony-in-c-5-part-six-whither-async
第一段指出:
结论是:
它的缺点是向后兼容性。
进一步阅读:
https:// /learn.microsoft.com/en-us/archive/blogs/ericlippert/asynchrony-in-c-5-part-one
I think perhaps this article covers the reasoning:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/asynchrony-in-c-5-part-six-whither-async
The first paragraph states:
It concludes:
The short of it is backwards compatibility.
Further reading:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/asynchrony-in-c-5-part-one
对我来说,最引人注目的原因是当函数变为异步时,return 语句的含义会发生变化。如果没有
asnyc
return x
表示“返回值为x
的任务”,而使用 async 则表示“将任务的结果设置为 <代码>x。For me, the most compelling reason is that the meaning of the
return
statement changes when a function becomesasync
. Withoutasnyc
return x
means "return a task with the valuex
", and with async it means "set the result of the task tox
.我写了摘要不久前我博客上的 async/await 关键字问题。
以下是“推断异步”部分的结论:
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
":