log日志bug修改
This commit is contained in:
@@ -1,18 +1,20 @@
|
||||
using UIShare.GlobalVariable;
|
||||
using Logger;
|
||||
using Prism.Ioc;
|
||||
using Prism.Mvvm;
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Reflection;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using UIShare.ViewModelBase;
|
||||
|
||||
namespace TestingModule.ViewModels
|
||||
{
|
||||
public class LogAreaViewModel : NavigateViewModelBase, IDisposable
|
||||
{
|
||||
|
||||
|
||||
// 日志集合
|
||||
private ObservableCollection<LogItem> _logs = new();
|
||||
|
||||
@@ -23,20 +25,23 @@ namespace TestingModule.ViewModels
|
||||
}
|
||||
public ICommand ClearLogCommand { get; set; }
|
||||
|
||||
private readonly ScopedContext _scopedContext;
|
||||
private readonly GlobalInfo _globalInfo;
|
||||
private IProgress<(string Message, Brush Color, int Depth)>? _logProgress;
|
||||
|
||||
public LogAreaViewModel(IContainerProvider containerProvider) : base(containerProvider)
|
||||
{
|
||||
ClearLogCommand = new DelegateCommand(ClearLog);
|
||||
_scopedContext = containerProvider.Resolve<ScopedContext>();
|
||||
_globalInfo = containerProvider.Resolve<GlobalInfo>();
|
||||
|
||||
// 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));
|
||||
});
|
||||
// 创建本作用域专属的日志接收器并注册到 ScopedContext
|
||||
_logProgress = new Progress<(string Message, Brush Color, int Depth)>(log =>
|
||||
{
|
||||
if (Logs == null) return;
|
||||
Logs.Add(new LogItem(log.Message, log.Color, log.Depth));
|
||||
});
|
||||
_scopedContext.LogProgress = _logProgress;
|
||||
}
|
||||
|
||||
private void ClearLog()
|
||||
@@ -51,16 +56,22 @@ namespace TestingModule.ViewModels
|
||||
{
|
||||
try
|
||||
{
|
||||
LoggerHelper.Progress = null!;
|
||||
// 注销本作用域的日志接收器,避免 Dispose 后仍收到旧消息
|
||||
if (_scopedContext != null && _scopedContext.LogProgress == _logProgress)
|
||||
{
|
||||
_scopedContext.LogProgress = null;
|
||||
}
|
||||
_logProgress = null;
|
||||
|
||||
if (Logs != null)
|
||||
{
|
||||
Logs.Clear();
|
||||
Logs = null!;
|
||||
Logs = null!;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LoggerHelper.ErrorWithNotify($"释放日志组件(LogAreaViewModel)资源失败: {ex.Message}");
|
||||
Logger.LoggerHelper.ErrorWithNotify(_scopedContext != null ? _globalInfo.CurrentScope : "", $"释放日志组件(LogAreaViewModel)资源失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user