Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ReadAsStringAsync async?

Tags:

c#

.net

.net-core

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);

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

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.

like image 284
jaredcnance Avatar asked Oct 27 '17 14:10

jaredcnance


1 Answers

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.

like image 53
SLaks Avatar answered Sep 24 '22 06:09

SLaks