即使使用Task,Blazor UI也会冻结

考虑Blazor WebAssembly App(托管ASP.NET Core)“空”项目。我对“计数器”页面进行了如下调整:

<button class="btn btn-primary" @onclick="IncrementCountAsync">Click me</button>

及其Counter.razor.cs文件:

public partial class Counter
{
    private static int currentCount = 0;

    private async Task IncrementCountAsync()
    {
        Console.WriteLine("Increment called");

        _ = HeavyComputeAsync();

        currentCount++;

        Console.WriteLine($"Counter = {currentCount}");
    }

    private static Task<int> HeavyComputeAsync()
    {
        return Task.Run(() =>
        {
            Console.WriteLine("Task start");

            for (long ndx = 0; ndx < 1000000; ++ndx)
                ndx.ToString();

            Console.WriteLine("Task end");
            return 0;
        });
    }
}

我正在将HeavyComputeAsync方法称为_ = ...,它不应等到​​IncrementCountAsync方法完成后,才应立即更新currentCount。

运行应用程序时,我可以在控制台中看到预期的行为:

Increment called
Counter = 1
Task start
Task end (after a while)

但是,UI冻结,它不会更新计数器。确切地说,有时它会立即更新:-O,但是在大多数情况下,仅在任务完成后才更新计数器。

我希望任务并行运行(在另一个线程中),并且不应阻止UI。

我知道IncrementCountAsync在这种情况下是同步运行的,因为我正在调用_ = HeavyComputeAsync。我试图用await = ...来调用它,但是即使在这种情况下,UI被冻结,我也无法单击其他页面。

如何实现UI即时更新?

谢谢,Csaba :-)