【发布时间】:2020-05-18 07:16:13
【问题描述】:
考虑 Blazor WebAssembly 应用程序(ASP.NET Core 托管)“空”项目。我将 Counter 页面调整如下:
<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 :-)
【问题讨论】:
-
您尝试改用
new TaskFactory().StartNew吗?或Task.Delay(1).ContinueWith
标签: c# asp.net-core task blazor