Blazor Timer call async API task to update UI

You probably don’t want to Invoke() the GetValue(), that would be rather pointless. You can implement the timer like this:

System.Threading.Timer timer;
protected override void OnInitialized()
{
    timer = new System.Threading.Timer(async _ =>  // async void
    {
        Time = await GetValue();
        // we need StateHasChanged() because this is an async void handler
        // we need to Invoke it because we could be on the wrong Thread          
        await InvokeAsync(StateHasChanged);
    }, null, 0, 1000);
}

I used a field to store the Timer because you should dispose it, add this to the Razor section:

@implements IDisposable

and this to the code:

public void Dispose()
{
    timer?.Dispose();
}

Leave a Comment