using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Avalonia.Threading;
using DispenserCommon.Aop;
using DispenserCommon.DTO;
using DispenserCommon.Events;
using DispenserCommon.Ioc;
using ReactiveUI;
namespace DispenserUI.ViewModels.Components;
///
/// 控制台日志
///
[Component, GlobalTry]
public class ConsoleLogVM : ViewModelBase
{
// 实现的最大行数
private const int MaxLines = 200;
private ObservableCollection _logs = [];
public ObservableCollection Logs
{
get => _logs;
set => this.RaiseAndSetIfChanged(ref _logs, value);
}
private readonly BlockingCollection _buffer = new(100);
///
/// 监听控制台日志
///
///
///
[EventAction(EventType.RollingLog)]
public void Listening(EventType type, LogMessage log)
{
_buffer.TryAdd(log);
}
///
/// 将日志渲染到界面
///
public void RenderLog()
{
Task.Run(() =>
{
foreach (var log in _buffer.GetConsumingEnumerable())
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (Logs.Count >= MaxLines) Logs.RemoveAt(0);
Logs.Add(log);
});
Task.Delay(100).Wait();
}
});
}
}