2023-12-28 15:18:03 +08:00
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
using System.Diagnostics.CodeAnalysis;
|
|
|
|
|
|
2024-02-02 17:14:41 +08:00
|
|
|
|
namespace MesETL.App.Services;
|
2023-12-28 15:18:03 +08:00
|
|
|
|
|
2024-01-04 09:00:44 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// 数据队列
|
|
|
|
|
/// </summary>
|
2023-12-29 16:16:05 +08:00
|
|
|
|
public class DataRecordQueue : IDisposable
|
2023-12-28 15:18:03 +08:00
|
|
|
|
{
|
2023-12-29 16:16:05 +08:00
|
|
|
|
private readonly BlockingCollection<DataRecord> _queue;
|
2023-12-28 15:18:03 +08:00
|
|
|
|
|
2023-12-29 16:16:05 +08:00
|
|
|
|
public int Count => _queue.Count;
|
|
|
|
|
public bool IsCompleted => _queue.IsCompleted;
|
|
|
|
|
public bool IsAddingCompleted => _queue.IsAddingCompleted;
|
2023-12-28 15:18:03 +08:00
|
|
|
|
|
2023-12-29 16:16:05 +08:00
|
|
|
|
public event Action? OnRecordWrite;
|
|
|
|
|
public event Action? OnRecordRead;
|
|
|
|
|
|
2024-02-08 17:38:23 +08:00
|
|
|
|
public DataRecordQueue() : this(500_000) // 默认容量最大500K
|
2023-12-28 15:18:03 +08:00
|
|
|
|
{
|
2024-01-29 09:29:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public DataRecordQueue(int boundedCapacity)
|
|
|
|
|
{
|
|
|
|
|
_queue = new BlockingCollection<DataRecord>(boundedCapacity);
|
2023-12-28 15:18:03 +08:00
|
|
|
|
}
|
|
|
|
|
|
2023-12-29 16:16:05 +08:00
|
|
|
|
public bool TryDequeue([MaybeNullWhen(false)] out DataRecord record)
|
2023-12-28 15:18:03 +08:00
|
|
|
|
{
|
2023-12-29 16:16:05 +08:00
|
|
|
|
if (_queue.TryTake(out record))
|
|
|
|
|
{
|
|
|
|
|
OnRecordRead?.Invoke();
|
|
|
|
|
return true;
|
|
|
|
|
}
|
2023-12-28 15:18:03 +08:00
|
|
|
|
|
2023-12-29 16:16:05 +08:00
|
|
|
|
return false;
|
2023-12-28 15:18:03 +08:00
|
|
|
|
}
|
|
|
|
|
|
2023-12-29 16:16:05 +08:00
|
|
|
|
public DataRecord Dequeue() => _queue.Take();
|
|
|
|
|
|
|
|
|
|
public void CompleteAdding() => _queue.CompleteAdding();
|
|
|
|
|
|
|
|
|
|
public void Enqueue(DataRecord record)
|
2023-12-28 15:18:03 +08:00
|
|
|
|
{
|
2023-12-29 16:16:05 +08:00
|
|
|
|
_queue.Add(record);
|
|
|
|
|
OnRecordWrite?.Invoke();
|
2023-12-28 15:18:03 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2023-12-29 16:16:05 +08:00
|
|
|
|
public void Dispose()
|
|
|
|
|
{
|
|
|
|
|
_queue.Dispose();
|
|
|
|
|
}
|
2023-12-28 15:18:03 +08:00
|
|
|
|
}
|