为什么存在 async 关键字 [英] Why does the async keyword exist

查看:59
本文介绍了为什么存在 async 关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浏览第 9 频道的 msdn 视频时,我发现了以下未答复的评论,希望有人能解释一下?

Browsing through the channel 9 msdn videos I found the following unanswered comment and was hoping someone could possibly explain it?

我不明白 async 关键字的意义.为什么不让任何时候方法返回 Task 时都使用 await 关键字,就像迭代器一样可以在任何返回 IEnumerable 的方法上产生回报.

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.

推荐答案

引入它主要是为了避免向后兼容性问题.如果必须由编译器推断方法的 async-ness(即通过检测 await 关键字),那么在一些微妙的情况下,现有代码会突然区别对待,特别是当您有标识符(称为 await 的变量或函数名称时).

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

这里有完整的解释:https://docs.microsoft.com/en-us/archive/blogs/ericlippert/asyncchrony-in-c-5-part-six-whither-async

这篇关于为什么存在 async 关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆