Search code examples
c#timerblazor

Blazor - How to stop a timer when exiting page


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!


Solution

  • 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
    }