Csa*_*aba 4 c# task asp.net-core blazor
考虑 Blazor WebAssembly App(ASP.NET Core 托管)“空”项目。我调整了 Counter 页面如下:
<button class="btn btn-primary" @onclick="IncrementCountAsync">Click me</button>
Run Code Online (Sandbox Code Playgroud)
及其 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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
我将HeavyComputeAsync方法称为_ = ...,它不应等到IncrementCountAsync方法完成,而应立即更新currentCount。
当我运行应用程序时,我可以在控制台中看到预期的行为:
Increment called
Counter = 1
Task start
Task end (after a while)
Run Code Online (Sandbox Code Playgroud)
但是 UI 冻结,它不会更新计数器。确切地说,有时它会立即更新:-O,但是大多数情况下,计数器仅在任务完成后更新。
我希望任务并行运行(在另一个线程中)并且不应该阻塞 UI。
我知道IncrementCountAsync在这种情况下同步运行,因为我正在调用_ = HeavyComputeAsync。我试图用await = ...调用它,但即使在这种情况下 UI 被冻结,我也无法单击其他页面。
如何实现UI即时更新?
谢谢,Csaba :-)
| 归档时间: |
|
| 查看次数: |
3401 次 |
| 最近记录: |