Consider the Blazor WebAssembly App (ASP. NET Core hosted) "empty" project. I adjusted the Counter page as follows:
<button class="btn btn-primary" @onclick="IncrementCountAsync">Click me</button>
and its Counter.razor.cs file:
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;
});
}
}
I'm calling the HeavyComputeAsync method as _ = ... which should not wait until the IncrementCountAsync method finishes, but immediately update the currentCount.
When I run the application I can see in the console the expected behavior:
Increment called
Counter = 1
Task start
Task end (after a while)
However the UI freezes, it does not update the counter. To be exact sometimes it immediately updates :-O, however most of the time the counter is updated after the task is finished only.
I expected the Task runs in parallel (in another thread) and should not block the UI.
I know the IncrementCountAsync runs synchronously in this case since I'm calling _ = HeavyComputeAsync. I tried to call it with await = ... but even in such case the UI is frozen, I can't click other pages.
How can I achieve the UI immediate update?
Thanks, Csaba :-)