使用"Async"时,为什么使用"Await"

When using "Async", why "Await" is used

我们使用"Async"这个词是为了让码流不阻塞主码流继续。还行吧。我们希望主流继续下去,而不必等待该过程完成。但通常,"Async and Await"是一起使用的。

我的问题是;当我们添加"await"时,我们期望码流中的状态是"Async"。在这种情况下,我不明白使用"Async"有什么好处?谁能解释一下,谢谢,辛苦了。

不清楚您指的是哪种技术。我假设您指的是过去几年添加到许多语言中的 asyncawait 关键字。

那么,这个说法其实是不正确的:

We use the term "Async" to allow the code stream to continue without blocking the main stream.

在 C#、JavaScript、Python、F# 和 Visual Basic 中,async 关键字 而不是 异步操作。它有两个作用:

  1. 在 method/lambda 中启用 await 关键字。
  2. 将 method/lambda 转换为状态机。

所以 async 不是 的意思 "run this code on a background thread" 或类似的东西,这是一个常见但不正确的假设。

上面的第一点对于向后兼容性很重要。这些语言中的每一种都使用 await 作为上下文关键字,因此程序中的文本 "await" 只有在标有 async 的方法中时才是关键字。这允许语言在不破坏任何现有代码的情况下引入新关键字(例如,某人的代码使用 await 作为变量名)。

请参阅 this post of mine which collected a lot of the discussion around the keywords as they were originally designed for C#/VB. Those same design decisions carried over almost exactly to other languages as they adopted the keywords, too. One of the resources linked from that post is Eric Lippert's post,了解除了 await 关键字之外我们还需要 async 关键字的原因。