Dispenser/DispenserCommon/Utils/BufferQueue.cs

50 lines
1.0 KiB
C#

namespace DispenserCommon.Utils;
/// <summary>
/// 缓冲队列
/// </summary>
public class BufferQueue<T>(int capacity)
{
private readonly Queue<T?> _queue = new();
private readonly int _capacity = Math.Min(capacity, 10);
private readonly object _lock = new();
// 尝试添加元素到队列中
public bool TryEnqueue(T? item)
{
lock (_lock)
{
if (_queue.Count >= _capacity) return false;
_queue.Enqueue(item);
return true;
}
}
// 尝试从队列中移除并返回元素
public bool TryDequeue(out T? result)
{
lock (_lock)
{
if (_queue.Count > 0)
{
result = _queue.Dequeue();
return true;
}
result = default(T);
return false;
}
}
// 获取当前队列中的元素数量
public int Count
{
get
{
lock (_lock)
{
return _queue.Count;
}
}
}
}