Parallel.Invoke(_po, async () => {
while(!_viewModel.DisConnect)
{
await _viewModel.SetThings();
await InvokeAsync(() => StateHasChanged());
Thread.Sleep(1000);
}
});
UI:
@foreach(var rsi in _viewModel.things)
{
<div class="row">
<div class="col text-center">
<span>Code: @things.Code</span>
</div>
<div class="col text-center">
<span>value: @(Math.Truncate(things.Value * 10000) / 10000)</span>
</div>
</div>
}
call Function and, call sateHasChanged every second for update UI. it's lagging. When I hover the mouse, it reacts after a 1~2 seconds.
how to update UI data every second without lagging on blazor wasm?
CodePudding user response:
The code is blocking itself. Parallel.Invoke
is used to execute multiple operations in parallel in a blocking way, but the question's code only has a single operation. This is no better than Task.Run(..).Wait()
. The delegate the tries to call the already blocked UI thread with InvokeAsync()
. And then freezes the thread for 1 second.
It would be simpler and better to use a simple loop and Task.Delay()
:
while(!_viewModel.DisConnect)
{
await _viewModel.SetThings();
StateHasChanged();
await Task.Delay(1000);
}
Even better, use a timer :
_timer = new System.Threading.Timer(async _ =>
{
await _viewModel.SetThings();
StateHasChanged();
},null, 0, 1000);
To stop the timer, call Dispose()
when needed:
_timer.Dispose();