简体   繁体   中英

HttpResponseMessage.Content.ReadAsStreamAsync() vs HttpResponseMessage.Content.ReadAsStringAsync()

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM