UPDATE:它是从json到锁定线程的类的转换。我已经尝试过使用较小的数据包进行相同的过程,并且UI并未冻结。那么问题是如何克服呢?
我试图从解析为类的JSON获取值:
public async Task<BitcoinDetails> GetData()
{
return await _httpClient.GetFromJsonAsync<BitcoinDetails>("https://localhost:5001/proxy");
}
我使用OnInitializedAsync将数据加载到视图中,但是以下代码锁定了UI
_bitcoinDetails = new BitcoinDetails();
_bitcoinDetails = await _bitcoinApiService.GetData();
var price = _bitcoinDetails.data.Find(x => x.symbol == "BTC");
if (price == null)
{
_bitcoinPrice = 0;
}
_bitcoinPrice = double.Parse(price.quote.USD.price.ToString());
如何在不锁定UI的情况下重组此代码以加载数据?
查看代码:
@if (_bitcoinDetails == null)
{
<p><em>Loading...</em></p>
}
else
{
<h3>BTC:@_bitcoinPrice</h3>
}
Blazor WebAssembly还没有真正的多线程支持。所有任务都有效地在与UI相同的线程上运行,这意味着执行任何耗时超过几毫秒的CPU密集型工作都可能导致用户界面出现明显的冻结。
不幸的是,直到.NET 6(2021年11月),Blazor WebAssembly中的多线程情况才可能得到改善。在此之前,解决方法是将短暂的暂停手动引入到CPU密集型任务的流程中,以便UI可以在这些中断期间控制并完成其工作:
async Task PerformCpuIntensiveWorkAsync()
{
for (int i = 0; i < 100; i++)
{
PerformOneHundredthOfWork();
await Task.Delay(1);
}
}
大多数JSON序列化程序提供低级API,可让您完全控制反序列化过程:
例如,如果需要反序列化大型JSON,其中包含100,000个汽车的数组
[
{ "make": "Ford", "model": "Mustang", "year": 2000 },
{ "make": "Honda", "model": "Civic", "year": 2005 },
{ "make": "Chevrolet", "model": "Corvette", "year": 2008 },
...
]
在 https://api.npoint.io/d159a22063995b37c52d下载此JSON
这是使用JSON.Net可以在反序列化过程中引入短暂休息的方法:
using Newtonsoft.Json;
using System.IO;
...
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
}
...
using var jsonStream = await Http.GetStreamAsync("https://api.npoint.io/d159a22063995b37c52d");
List<Car> cars = await DeserializeCarsAsync(jsonStream);
static async Task<List<Car>> DeserializeCarsAsync(Stream jsonStream)
{
using var streamReader = new StreamReader(jsonStream);
using var jsonReader = new JsonTextReader(streamReader);
var serializer = new JsonSerializer();
if (!jsonReader.Read())
throw new JsonException($"Deserialization failed at line {jsonReader.LineNumber} position {jsonReader.LinePosition}.");
if (jsonReader.TokenType != JsonToken.StartArray)
throw new JsonException($"Deserialization failed at line {jsonReader.LineNumber} position {jsonReader.LinePosition}.");
List<Car> cars = new List<Car>();
while (true)
{
if (!jsonReader.Read())
throw new JsonException($"Deserialization failed at line {jsonReader.LineNumber} position {jsonReader.LinePosition}.");
if (jsonReader.TokenType == JsonToken.EndArray)
return cars;
if (jsonReader.TokenType != JsonToken.StartObject)
throw new JsonException($"Deserialization failed at line {jsonReader.LineNumber} position {jsonReader.LinePosition}.");
var car = serializer.Deserialize<Car>(jsonReader);
cars.Add(car);
// Pause after every 10th deserialized car:
if (cars.Count % 10 == 0)
await Task.Delay(1);
}
}
如果您必须处理嵌套集合,它看起来确实过于复杂,甚至变得更糟,但是它解决了这个问题。
如果可能,使用较小的JSON。看来您正在使用代理从CoinMarketCap获取报价或列表。您可以获得整个列表,但只需要一项-BTC。在不知道详细信息是否适合您的情况下很难说,但是有可能要求CoinMarketCap服务器为您过滤结果并仅返回BTC报价的数据-这将产生更小的JSON:https:// sandbox -api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?CMC_PRO_API_KEY=b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c&symbol=BTC。
尝试更快的JSON序列化器。Utf8Json看起来很有希望。
如果您只需要从大型JSON反序列化一些字段,则有许多潜在的优化方法:
Quote
对象并且只需要获取其价格,请尝试使用具有only属性的类Price
反序列化为:class Quote { decimal Price {get; set;} }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句