RingBuffer.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace MvvmScaffoldFrame48.DLL.SystemTools
  7. {
  8. public sealed class RingBuffer<T>
  9. {
  10. private readonly T[] _buffer;
  11. private int _writeIndex;
  12. private int _readIndex;
  13. private int _count;
  14. private readonly int _capacity;
  15. private readonly object _lock = new object();
  16. public RingBuffer(int capacity)
  17. {
  18. _capacity = capacity;
  19. _buffer = new T[capacity];
  20. }
  21. public bool TryEnqueue(T item)
  22. {
  23. lock (_lock)
  24. {
  25. if (_count >= _capacity) return false;
  26. var index = (_readIndex + _count) % _capacity;
  27. _buffer[index] = item;
  28. _count++;
  29. return true;
  30. }
  31. }
  32. public bool TryDequeue(out T result)
  33. {
  34. lock (_lock)
  35. {
  36. if (_count <= 0)
  37. {
  38. result = default(T);
  39. return false;
  40. }
  41. result = _buffer[_readIndex];
  42. _buffer[_readIndex] = default(T); // 避免内存泄漏
  43. _readIndex = (_readIndex + 1) % _capacity;
  44. _count--;
  45. return true;
  46. }
  47. }
  48. public int Count => _count;
  49. }
  50. }