为什么 WebRequest.GetResponseAsync() 不是异步的?

Why isn't WebRequest.GetResponseAsync() async?

据我所知 WebRequest.GetResponseAsync() 可以等待并且是异步的。 但是当我在 https://referencesource.microsoft.com/#System/net/System/Net/WebRequest.cs,99a2a9c8ebc067dc 查看它的源代码时 它不是用 "async" 关键字定义的。

我以为您不能等待未定义为 "async" 的方法?

I thought you cannot await a method that is not defined as "async"?

这是一种 "shorthand" 的思考方式,在最初学习 async 时可能很有用,但当您获得更多关于 async/[= 的知识时就会分崩离析12=]。这句话有两个概念不太对

首先,代码不能await一个方法。实际发生的是该方法被调用,就像任何其他方法一样。该方法 return 是一个值 - 一个 awaitable 类型 - 实际上等待的是 return 值。我们经常谈论 "awaiting a method",但 "calling a method and awaiting its return value" 只是 shorthand,这更准确,但对于大多数对话来说太尴尬了。

其次,async 只是一种方法 来创建可等待的 return 值(然后可以等待)。还有其他几种方法。例如,如果您有一个使用 older APM asynchronous pattern, and you want to use it with await. In that case, you would normally write wrapper methods that return Task<T> and are implemented using Task<T>.Factory.FromAsync (without async). Another common approach is to use TaskCompletionSource<T>, which can create a Task<T> around any kind of logical "future event".

的 API,则通常使用 Task<T>.Factory.FromAsync

换句话说,async是一个实现细节。接口方法可以声明为 returning Task 并等待,但只有方法 implementations 可以用 [=10 声明=].