Blazor - How to stop a timer when exiting page

Viewed 771

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!

1 Answers

On top of the markup section

 @implements IDisposable

And in @code

// var timer = new Timer();
   _timer = new Timer();     // make it a field



public void Dispose()
{
   _timer?.Dispose();        // because you need it here
}
Related