I have an extremely simple example from the standard Blazor server-side template that shows that a timer function will not update the UI even after a StateHasChanged(); call has been made.
The log output shows the timmer being triggered and if I wait a few seconds and click the IncrementCount button the count value jumps to the number of times the counter has been incremented by the timer.
Very curious ... any help would be greatly appreciated
Kind regards, Stuart
@page "/counter"
@using System.Timers;
@using Microsoft.Extensions.Logging
@inject ILogger<Counter> Logger
<h1>Counter</h1>
<p>Current count: @(currentCount.ToString())</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
public System.Timers.Timer timer;
protected override async Task OnInitializedAsync()
{
timer = new Timer(1000);
timer.Elapsed += this.OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
timer.Start();
}
public void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Logger.LogInformation("Timer triggered");
IncrementCount();
StateHasChanged();
}
}