Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor - How to stop a timer when exiting page

Tags:

c#

timer

blazor

I have a razor page/component that start a timer in the overriden OnInitializedAsync method. It uses an API client to fetch an IEnumerable every 500 milliseconds :

 protected override async Task OnInitializedAsync()
    {
        _interfaceConnections = await _client.GetAllInterfaceConnections();

        var timer = new Timer();
        timer.Elapsed += new ElapsedEventHandler(UpdateConnections);
        timer.Interval = 500;
        timer.Enabled = true;
    }

    private async void UpdateConnections(object source, ElapsedEventArgs e)
    {
        _interfaceConnections = await _client.GetAllInterfaceConnections();

        await InvokeAsync(StateHasChanged);
    }

How do I stop this timer when navigating away from this component? There is no equivalent override for OnUnloadedAsync or something of that nature. Because this timer never stops it is continuously making database calls and never stops!

like image 320
Martin Avatar asked Sep 11 '25 14:09

Martin


1 Answers

On top of the markup section

 @implements IDisposable

And in @code

private Timer? _timer;
protected override async Task OnInitializedAsync()
{
  //var timer = new Timer();    
       _timer = new Timer();     // store it in a field

  ... the rest, as before
}

public void Dispose()
{
   _timer?.Dispose();           // because you need it here
}
like image 127
Henk Holterman Avatar answered Sep 13 '25 05:09

Henk Holterman