var request = new HttpRequestMessage(HttpMethod.Get, $"api/Items");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var response = await _httpClient.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var stream = await response.Content.ReadAsStreamAsync();
using (var streamReader = new StreamReader(stream))
{
using (var jsonTextReader = new JsonTextReader(streamReader))
{
var jsonSerializer = new JsonSerializer();
var data = jsonSerializer.Deserialize<Item>(jsonTextReader);
}
}
}
...
var request = new HttpRequestMessage(HttpMethod.Get, "api/Items");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<List<Item>>(content);
I've run this two examples and I'm curious what is the difference between them that always getting same result, ReadAsStreamAsync is much faster then ReadAsStringAsync.
ReadAsStreamAsync()Serialize the HTTP content and return a stream that represents the content as an asynchronous operation.
ReadAsStringAsync() Serialize the HTTP content to a string as an asynchronous operation. ReadAsStringAsync(CancellationToken) Serialize the HTTP content to a string as an asynchronous operation.
Under the hood, HttpClient
stores content in MemoryStream
. So, basically calling ReadAsStreamAsync
just returns a reference to the stream. In the case of calling ReadAsStringAsync
, ToArray
method is called on memory stream so an additional copy of data is created.
You can check description for ReadAsStreamAsync and for ReadAsStringAsync
In few words - you can send to request content not only string. And ReadAsStreamAsync is only way for you here. If your response content is string - you can use both. But Stream is faster in Any Time.
This gives good explanation about memory allocation and perfomanse in these cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With