Blazor - 退出页面时如何停止计时器

Blazor - How to stop a timer when exiting page

我有一把剃须刀 page/component,它在覆盖的 OnInitializedAsync 方法中启动一个计时器。它使用 API 客户端每 500 毫秒获取一个 IEnumerable :

 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);
    }

离开此组件时如何停止此计时器? OnUnloadedAsync 或类似性质的东西没有等效的覆盖。因为这个计时器从不停止,所以它不断地进行数据库调用并且从不停止!

在标记部分的顶部

 @implements IDisposable

并在@code

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



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