using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MvvmScaffoldFrame48.DLL.SystemTools { public sealed class RingBuffer { private readonly T[] _buffer; private int _writeIndex; private int _readIndex; private int _count; private readonly int _capacity; private readonly object _lock = new object(); public RingBuffer(int capacity) { _capacity = capacity; _buffer = new T[capacity]; } public bool TryEnqueue(T item) { lock (_lock) { if (_count >= _capacity) return false; var index = (_readIndex + _count) % _capacity; _buffer[index] = item; _count++; return true; } } public bool TryDequeue(out T result) { lock (_lock) { if (_count <= 0) { result = default(T); return false; } result = _buffer[_readIndex]; _buffer[_readIndex] = default(T); // 避免内存泄漏 _readIndex = (_readIndex + 1) % _capacity; _count--; return true; } } public int Count => _count; } }