简体   繁体   English

ReadAsAsync和JsonConvert之间的区别

[英]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. 前者从流中异步读取,然后使用线程池线程将JSON字符串反序列化为对象。

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. 后者从流中异步读取,但是在等待从流中异步读取之后恢复的线程上同步地将JSON字符串转换为对象。

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. 在内部,两种方法都将利用Json.NET来解析数据,因为扩展方法HttpContentExtensions.ReadAsAsync<T>将在内部调用JsonMediaTypeFormatter ,后者使用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. 但是,测试您的代码,看看它是否适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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