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

Mar*_*tin 4 c# timer blazor

我有一个剃刀页面/组件,它在重写的 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);
    }
Run Code Online (Sandbox Code Playgroud)

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

Hen*_*man 12

在标记部分的顶部

 @implements IDisposable
Run Code Online (Sandbox Code Playgroud)

在@code中

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



public void Dispose()
{
   _timer?.Dispose();        // because you need it here
}
Run Code Online (Sandbox Code Playgroud)