为什么ReadAsStringAsync异步?

jar*_*nce 11 .net c# .net-core

那么,在下面的代码片段中,为什么ReadAsStringAsync是异步方法?

var response = await _client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)

最初我希望SendAsync发送请求并将响应流加载到内存中,此时读取该流将是进程内CPU工作(而不是真正的异步).

走下源代码兔洞,我到达了这个:

 int count = await _stream.ReadAsync(destination, cancellationToken).ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)

https://github.com/dotnet/corefx/blob/0aa654834405dcec4aaa9bd416b2b31ab8d3503e/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnection.cs#L967

这让我觉得可能连接是打开的,直到响应流实际从进程外的某些源读取?我完全相信我缺少一些关于Http Connections流如何工作的基础知识.

SLa*_*aks 14

SendAsync()等待请求完成并且响应开始到达.

它不会缓冲整个响应; 这使您可以流式传输大型响应,而无需将整个响应保留在内存中.