FixSizeQueue.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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; private 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. }
  33. }
  34. public bool TryDequeue(out T obj)
  35. {
  36. lock (_locker)
  37. {
  38. obj = default (T);
  39. if (_innerQueue.Count > 0)
  40. {
  41. obj = _innerQueue.Dequeue();
  42. return true;
  43. }
  44. return false;
  45. }
  46. }
  47. public List<T> ToList()
  48. {
  49. lock (_locker)
  50. {
  51. return _innerQueue.ToList();
  52. }
  53. }
  54. public void Clear()
  55. {
  56. lock (_locker)
  57. {
  58. _innerQueue.Clear();
  59. }
  60. }
  61. public T ElementAt(int index)
  62. {
  63. lock (_locker)
  64. {
  65. return _innerQueue.ElementAt(index);
  66. }
  67. }
  68. public bool IsEmpty()
  69. {
  70. lock (_locker)
  71. {
  72. return _innerQueue.Count==0;
  73. }
  74. }
  75. }
  76. }