Reputation: 742
So, in the following snippet, why is ReadAsStringAsync an async method?
var response = await _client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
Originally I expected SendAsync to send the request and load the response stream into memory at which point reading that stream would be in-process CPU work (and not really async).
Going down the source code rabbit hole, I arrived at this:
int count = await _stream.ReadAsync(destination, cancellationToken).ConfigureAwait(false);
This makes me think that maybe the connection is open until the response stream is actually read from some source outside of the process? I fully expect that I am missing some fundamentals regarding how streams from Http Connections work.
Upvotes: 14
Views: 1547
Reputation: 887877
SendAsync()
waits for the request to finish and the response to start arriving.
It doesn't buffer the entire response; this allows you to stream large responses without ever holding the entire response in memory.
Upvotes: 19