88 lines
2.1 KiB
C#
88 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using YwxAppWpfDanMu.Services;
|
|
|
|
namespace YwxAppWpfDanMu.Utils
|
|
{
|
|
public class DanMuQueueProcessor
|
|
{
|
|
private readonly DanMuDispatcher _dispatcher;
|
|
private readonly Queue<Action> _queue = new Queue<Action>();
|
|
private bool _isProcessing;
|
|
|
|
public DanMuQueueProcessor(DanMuDispatcher dispatcher)
|
|
{
|
|
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
|
|
}
|
|
|
|
public void Enqueue(Action action)
|
|
{
|
|
lock (_queue)
|
|
{
|
|
_queue.Enqueue(action);
|
|
|
|
if (!_isProcessing)
|
|
{
|
|
_isProcessing = true;
|
|
_dispatcher.BeginInvoke(ProcessQueue);
|
|
}
|
|
}
|
|
}
|
|
|
|
public void EnqueueBatch(Action batchAction)
|
|
{
|
|
Enqueue(() =>
|
|
{
|
|
var actions = new List<Action>();
|
|
batchAction();
|
|
|
|
// 处理批处理逻辑
|
|
lock (_queue)
|
|
{
|
|
while (_queue.Count > 0)
|
|
{
|
|
actions.Add(_queue.Dequeue());
|
|
}
|
|
}
|
|
|
|
// 执行所有动作
|
|
foreach (var action in actions)
|
|
{
|
|
action();
|
|
}
|
|
});
|
|
}
|
|
|
|
private void ProcessQueue()
|
|
{
|
|
Action action = null;
|
|
|
|
lock (_queue)
|
|
{
|
|
if (_queue.Count > 0)
|
|
{
|
|
action = _queue.Dequeue();
|
|
}
|
|
else
|
|
{
|
|
_isProcessing = false;
|
|
return;
|
|
}
|
|
}
|
|
|
|
try
|
|
{
|
|
action();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// 记录错误日志
|
|
}
|
|
finally
|
|
{
|
|
_dispatcher.BeginInvoke(ProcessQueue);
|
|
}
|
|
}
|
|
}
|
|
} |