FixSizeQueue.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Collections.Concurrent;
  6. namespace Aitex.Core.Util
  7. {
  8. public class FixSizeQueue<T>
  9. {
  10. public int FixedSize { get; set; }
  11. public int Count {
  12. get
  13. {
  14. lock (_locker)
  15. {
  16. return _innerQueue.Count;
  17. }
  18. }
  19. }
  20. private Queue<T> _innerQueue;
  21. private object _locker = new object();
  22. public FixSizeQueue(int size)
  23. {
  24. FixedSize = size;
  25. _innerQueue = new Queue<T>();
  26. }
  27. public void Enqueue(T obj)
  28. {
  29. lock (_locker)
  30. {
  31. _innerQueue.Enqueue(obj);
  32. while (_innerQueue.Count > FixedSize)
  33. {
  34. _innerQueue.Dequeue();
  35. }
  36. }
  37. }
  38. public bool TryDequeue(out T obj)
  39. {
  40. lock (_locker)
  41. {
  42. obj = default (T);
  43. if (_innerQueue.Count > 0)
  44. {
  45. obj = _innerQueue.Dequeue();
  46. return true;
  47. }
  48. return false;
  49. }
  50. }
  51. public List<T> ToList()
  52. {
  53. lock (_locker)
  54. {
  55. return _innerQueue.ToList();
  56. }
  57. }
  58. public void Clear()
  59. {
  60. lock (_locker)
  61. {
  62. _innerQueue.Clear();
  63. }
  64. }
  65. public T ElementAt(int index)
  66. {
  67. lock (_locker)
  68. {
  69. return _innerQueue.ElementAt(index);
  70. }
  71. }
  72. public bool IsEmpty()
  73. {
  74. lock (_locker)
  75. {
  76. return _innerQueue.Count==0;
  77. }
  78. }
  79. }
  80. }