Blazor UI 锁定

Jed*_*Jed 6 c# asp.net-core blazor

更新:它是从 json 到锁定线程的类的转换。我已经用较小的数据包尝试了相同的过程,并且 UI 没有冻结。所以问题是如何克服这个问题?

我试图从解析为类的 JSON 中获取值:

 public async Task<BitcoinDetails> GetData()
    {

        return await _httpClient.GetFromJsonAsync<BitcoinDetails>("https://localhost:5001/proxy");

    }
Run Code Online (Sandbox Code Playgroud)

我使用 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());
Run Code Online (Sandbox Code Playgroud)

如何重构此代码以在不锁定 UI 的情况下加载数据?

查看代码:

 @if (_bitcoinDetails == null)
{
    <p><em>Loading...</em></p>
}
else
{
<h3>BTC:@_bitcoinPrice</h3>
}
Run Code Online (Sandbox Code Playgroud)

A. *_*lto 7

Blazor WebAssembly 中的多线程

Blazor WebAssembly 还没有真正的多线程支持。所有任务都在与 UI 相同的线程上有效运行,这意味着执行时间超过几毫秒的任何 CPU 密集型工作都可能导致用户界面明显冻结。

不幸的是,Blazor WebAssembly 中的多线程情况在 .NET 6(2021 年 11 月)之前不太可能改善。在此之前,解决方法是在 CPU 密集型任务流中手动引入短暂的暂停,以便 UI 可以在这些中断期间进行控制并完成其工作:

async Task PerformCpuIntensiveWorkAsync()
{
    for (int i = 0; i < 100; i++)
    {
        PerformOneHundredthOfWork();
        await Task.Delay(1);
    }
}
Run Code Online (Sandbox Code Playgroud)

大型 JSON 的反序列化

大多数 JSON 序列化器提供低级 API,让您可以完全控制反序列化过程:

如果您需要反序列化一个大型 JSON,例如,包含 100,000 辆汽车的数组

[
  { "make": "Ford", "model": "Mustang", "year": 2000 },
  { "make": "Honda", "model": "Civic", "year": 2005 },
  { "make": "Chevrolet", "model": "Corvette", "year": 2008 },
  ...
]
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您必须处理嵌套集合,它确实看起来过于复杂并且变得更糟,但它解决了问题。

其他选项

  • 如果可能,使用较小的 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对象并且只需要获取它们的价格,请尝试使用具有唯一属性的类Price来反序列化为:class Quote { decimal Price {get; set;} }
    • 尝试使用JsonDocument仅反序列化您需要的特定 JSON 节点。它仍然需要首先解析整个 JSON 以创建其节点的映射,但无论如何它应该比反序列化整个 JSON 更快。
    • 如果您使用序列化程序的低级 API,它们中的大多数允许在解析时跳过 JSON 元素(JsonReader.SkipUtf8JsonReader.SkipJsonReader.ReadNextBlock等)。