44

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

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

我确信有充分的理由,我只是想了解为什么上述建议是不可能的。

4

4 回答 4

24

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

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

于 2012-02-10T09:58:38.887 回答
15

我想也许这篇文章涵盖了推理:

https://docs.microsoft.com/en-us/archive/blogs/ericlippert/asynchrony-in-c-5-part-six-whither-async

第一段说:

许多人问我是什么促使设计决定要求任何包含“await”表达式的方法都以上下文关键字“async”为前缀。

它得出结论:

这有很多优点和缺点。在评估了所有这些,并大量使用原型编译器来了解它的感觉之后,C# 设计者决定在包含“await”的方法上要求“async”。我认为这是一个合理的选择。

它的缺点是向后兼容。

进一步阅读:

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

于 2012-02-10T09:58:22.443 回答
10

对我来说,最令人信服的原因是return当函数变为async. 没有asnyc return x意味着“返回具有值的任务x”,而异步意味着“将任务的结果设置为x.

于 2012-02-10T10:05:06.880 回答
3

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.

于 2012-02-10T13:38:03.420 回答