Blazor WebAssembly .NET 6.0页面无用户活动检测实现方法问询
在Blazor WebAssembly .NET 6.0中检测用户无活动状态
实现思路
通过监听用户鼠标、键盘、触摸等操作事件,每次触发操作时重置计时器;当计时器达到设定时长(60秒)未被重置时,执行指定方法。以下是单页面组件级的具体实现步骤:
步骤1:声明变量与实现资源清理接口
在页面组件类中声明计时器、超时时长变量,并实现IDisposable接口以避免内存泄漏:
public partial class YourPage : IDisposable { private System.Timers.Timer _inactivityTimer; private const int _timeoutSeconds = 60; }
步骤2:初始化计时器与绑定操作事件
在组件首次渲染完成后,初始化计时器,并在页面根元素上绑定用户操作事件:
protected override void OnAfterRender(bool firstRender) { if (firstRender) { InitializeInactivityTimer(); } base.OnAfterRender(firstRender); } private void InitializeInactivityTimer() { _inactivityTimer = new System.Timers.Timer(_timeoutSeconds * 1000); _inactivityTimer.Elapsed += OnInactivityTimeout; _inactivityTimer.AutoReset = false; // 超时后仅触发一次,重置操作后重新启动 _inactivityTimer.Start(); }
在组件根元素绑定操作事件,触发计时器重置:
<div @onmousemove="ResetTimer" @onkeydown="ResetTimer" @onclick="ResetTimer" @ontouchstart="ResetTimer"> <!-- 页面内容区域 --> </div>
步骤3:实现计时器重置与超时逻辑
编写重置计时器的方法,以及超时后执行的指定业务方法:
private void ResetTimer() { if (_inactivityTimer == null) return; _inactivityTimer.Stop(); _inactivityTimer.Start(); } private void OnInactivityTimeout(object sender, System.Timers.ElapsedEventArgs e) { // 计时器事件在非UI线程触发,需切换回UI线程执行操作 InvokeAsync(() => { ExecuteTargetMethod(); }); } // 替换为你需要执行的指定方法 private void ExecuteTargetMethod() { // 示例:执行业务逻辑,如弹窗提示、清理数据等 Console.WriteLine("用户已60秒无操作,触发指定方法"); }
步骤4:清理资源
在组件销毁时释放计时器资源:
public void Dispose() { _inactivityTimer?.Stop(); _inactivityTimer?.Dispose(); }
额外说明
- 若需多页面复用,可将上述逻辑封装为可注入服务,通过依赖注入在各页面调用
- 可根据需求添加更多监听事件(如
onscroll),覆盖更多用户操作场景 - 若页面包含iframe或第三方控件,需额外处理这些区域的事件监听
内容的提问来源于stack exchange,提问作者marcoqf73
相关产品推荐
相关产品推荐

