My ChangeValues server-side event occurs every 5 seconds but on client-side, I only see the first value of the number variable. See code below
@page "/"
<button class="btn btn-primary" @onclick="ChangeValues">Click me</button>
<b>@number</b>
@code {
double number;
private Random rnd = new Random();
private System.Threading.Timer _timer;
void ChangeValues()
{
number = rnd.NextDouble();
Console.WriteLine(number);
}
private void DoWork(object state)
{
ChangeValues();
}
protected override async Task OnInitializedAsync()
{
_timer = new System.Threading.Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(5));
}
}
When you use a Timer (that will fire on another Thread) you have to call StateHasChanged() using Invoke:
private async void DoWork(object state)
{
ChangeValues();
await InvokeAsync(StateHasChanged);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With