在我的 Blazor 服务器端应用程序中,我想在用户离开 Razor 页面并更改到另一个页面时运行代码。我怎样才能做到这一点?

问题描述 投票:0回答:1

我有以下用例: 我有一个剃刀页面,用户可以在其中连接到远程计算机并监视其过程值。当他进入相关页面时,将自动从远程机器循环读取值。 (使用 OnInitialized())

我希望,当用户切换到另一个页面时,循环读取停止或暂停。目前它正在后台继续进行。 (数据不会记录在任何地方)

当用户使用以下代码打开页面时,我可以开始阅读操作。我需要一个类似的事件来离开页面,以便我可以运行代码来停止或暂停循环阅读。我怎样才能做到这一点?

protected override void OnInitialized()
{      
  // starting cycling reading when page entered
  Read_cyclic_values();
}

public void Read_cyclic_values()
{
  // code for cycling reading in connection with a scoped service
}
c# blazor-server-side razor-pages
1个回答
0
投票

也许是这样的?

@implements IDisposable
@inject NavigationManager NavigationManager

//Your HTML

@code
{
    protected override void OnInitialized()
    {
    // Subscribe to the event
        NavigationManager.LocationChanged += LocationChanged;
        Read_cyclic_values();
        base.OnInitialized();
    }

    void Read_cyclic_values()
    {
    // code for cycling reading in connection with a scoped service
    }

    void LocationChanged(object sender, LocationChangedEventArgs e)
    {
    //Do what you need to do to stop the cycle
    }

    void IDisposable.Dispose()
    {
    // Unsubscribe from the event when your component is disposed
        NavigationManager.LocationChanged -= LocationChanged;
    }
}

我认为您也可以在 Dispose 中定义循环断路器

© www.soinside.com 2019 - 2024. All rights reserved.