简体   繁体   中英

Difference between ReadAsAsync and JsonConvert

This works for all properties:

string resultAsString = await httpResponseMessage.Content.ReadAsStringAsync();
return await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<ApiData>(resultAsString));

while this works only for some of them:

return await httpResponseMessage.Content.ReadAsAsync<ApiData>();

what is the difference?

The former reads asynchronously from the stream , and then uses a thread-pool thread to deserialize the JSON string to an object.

The latter reads asynchronously from the stream, but transforms the JSON string to an object synchronously , on the thread in which resumed after awaiting the asynchronous read from the stream.

Internally, both methods will utilize Json.NET to parse the data, as the extension method HttpContentExtensions.ReadAsAsync<T> will internally call the JsonMediaTypeFormatter , which uses Json.NET.

Personally, I'd use the latter, as I see no benefit in executing the serialization on a background thread. But, test your code and see if that works for you.

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