DIspose添加

This commit is contained in:
hsc
2026-06-11 15:45:29 +08:00
parent 9c661200b9
commit 5cac253cb8
8 changed files with 164 additions and 17 deletions

View File

@@ -17,7 +17,7 @@ using Prism.Events;
namespace TestingModule.ViewModels
{
public class StepsManagerViewModel:NavigateViewModelBase
public class StepsManagerViewModel:NavigateViewModelBase, IDisposable
{
#region
private string _Title;
@@ -231,7 +231,50 @@ namespace TestingModule.ViewModels
}
}
#endregion
public void Dispose()
{
try
{
// 1. 【核心修复】必须取消订阅 CollectionChanged 事件,否则 VM 永远无法被释放
if (Program != null)
{
if (Program.StepCollection != null)
{
Program.StepCollection.CollectionChanged -= StepCollection_CollectionChanged;
}
if (Program.ErrorStepCollection != null)
{
Program.ErrorStepCollection.CollectionChanged -= StepCollection_CollectionChanged;
}
}
// 2. 【核心修复】必须显式退订 Prism 全局事件AlarmEvent
// 注意:因为订阅时使用的是匿名 Lambda最安全稳妥的退订方式是把整个事件上的当前 VM 订阅者全部注销
_eventAggregator?.GetEvent<AlarmEvent>()?.Unsubscribe(null);
// 3. 清空临时缓存集合与 UI 绑定列表,避免悬挂指针
tmpCopyList?.Clear();
tmpCopyList = null!;
SelectedItems?.Clear();
SelectedItems = null!;
// 4. 清除选中项状态引用
SelectedStep = null;
if (_ScopedContext != null)
{
_ScopedContext.SelectedStep = null;
_ScopedContext = null!; // 断开上下文引用
}
}
catch (Exception ex)
{
Logger.LoggerHelper.Error($"释放步骤管理组件StepsManagerViewModel资源失败: {ex.Message}");
}
}
}
}