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

@@ -11,12 +11,11 @@ using UIShare.ViewModelBase;
namespace TestingModule.ViewModels
{
public class LogAreaViewModel : NavigateViewModelBase
public class LogAreaViewModel : NavigateViewModelBase, IDisposable
{
// 日志集合
private ObservableCollection<LogItem> _logs = new();
public ObservableCollection<LogItem> Logs
{
get => _logs;
@@ -27,18 +26,42 @@ namespace TestingModule.ViewModels
public LogAreaViewModel(IContainerProvider containerProvider) : base(containerProvider)
{
ClearLogCommand = new DelegateCommand(ClearLog);
// 2. 保持原有逻辑,但请确保在 Dispose 中对其进行清理
LoggerHelper.Progress = new System.Progress<(string message, string color, int depth)>(
log =>
{
// 增加防御性代码:防止进入销毁流程时异步回调引发空引用异常
if (Logs == null) return;
var brush = (Brush)new BrushConverter().ConvertFromString(log.color);
Logs.Add(new LogItem(log.message, brush, log.depth));
});
}
private void ClearLog()
{
Logs.Clear();
Logs?.Clear();
}
/// <summary>
/// 完善后的资源释放方法
/// </summary>
public void Dispose()
{
try
{
LoggerHelper.Progress = null!;
if (Logs != null)
{
Logs.Clear();
Logs = null!;
}
}
catch (Exception ex)
{
Logger.LoggerHelper.ErrorWithNotify($"释放日志组件LogAreaViewModel资源失败: {ex.Message}");
}
}
}