SSPC-Tester/SSPCTester.UI/Services/UiLogSink.cs
2026-06-30 12:10:29 +08:00

36 lines
1.0 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.ObjectModel;
using System.Windows.Threading;
namespace SSPCTester.UI.Services;
/// <summary>
/// UI 日志接收器:把日志事件投递到 UI 线程的 ObservableCollection供日志面板绑定。
/// </summary>
public sealed class UiLogSink
{
private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;
public ObservableCollection<LogEntry> Entries { get; } = new();
public int MaxEntries { get; set; } = 500;
public void Add(UiLogLevel level, string message)
{
var entry = new LogEntry(DateTime.Now, level, message);
if (_dispatcher.CheckAccess()) Append(entry);
else _dispatcher.BeginInvoke(() => Append(entry));
}
private void Append(LogEntry entry)
{
Entries.Add(entry);
while (Entries.Count > MaxEntries) Entries.RemoveAt(0);
}
}
public enum UiLogLevel { Info, Success, Warning, Error }
public sealed record LogEntry(DateTime Time, UiLogLevel Level, string Message)
{
public string TimeText => Time.ToString("HH:mm:ss.fff");
}