/src/Nancy/Diagnostics/ConcurrentLimitedCollection.cs

http://github.com/NancyFx/Nancy · C# · 90 lines · 44 code · 9 blank · 37 comment · 2 complexity · c2e09d1070811be36c320c749ad59ee7 MD5 · raw file

  1. namespace Nancy.Diagnostics
  2. {
  3. using System.Collections;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. /// <summary>
  7. /// Provides a thread safe, limited size, collection of objects
  8. /// If the collection is full the oldest item gets removed.
  9. /// </summary>
  10. /// <typeparam name="T">Type to store</typeparam>
  11. public class ConcurrentLimitedCollection<T> : IEnumerable<T>
  12. {
  13. private readonly int maxSize;
  14. private ConcurrentQueue<T> internalStore;
  15. /// <summary>
  16. /// Gets the current size for the collection.
  17. /// </summary>
  18. /// <value> Current size of the collection.</value>
  19. public int CurrentSize
  20. {
  21. get
  22. {
  23. return this.internalStore.Count;
  24. }
  25. }
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="ConcurrentLimitedCollection{T}"/> class, with
  28. /// the provided <paramref name="maxSize"/>.
  29. /// </summary>
  30. /// <param name="maxSize">The maximum size for the collection.</param>
  31. public ConcurrentLimitedCollection(int maxSize)
  32. {
  33. this.maxSize = maxSize;
  34. this.internalStore = new ConcurrentQueue<T>();
  35. }
  36. /// <summary>
  37. /// Returns an enumerator that iterates through the collection.
  38. /// </summary>
  39. /// <returns>
  40. /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
  41. /// </returns>
  42. /// <filterpriority>1</filterpriority>
  43. public IEnumerator<T> GetEnumerator()
  44. {
  45. return this.internalStore.GetEnumerator();
  46. }
  47. /// <summary>
  48. /// Returns an enumerator that iterates through a collection.
  49. /// </summary>
  50. /// <returns>
  51. /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
  52. /// </returns>
  53. /// <filterpriority>2</filterpriority>
  54. IEnumerator IEnumerable.GetEnumerator()
  55. {
  56. return this.GetEnumerator();
  57. }
  58. /// <summary>
  59. /// Adds an item to the collection.
  60. /// If the collection is full, the oldest item is removed and the new item
  61. /// is added to the end of the collection.
  62. /// </summary>
  63. /// <param name="item">Item to add</param>
  64. public void Add(T item)
  65. {
  66. if (this.internalStore.Count == this.maxSize)
  67. {
  68. T temp;
  69. this.internalStore.TryDequeue(out temp);
  70. }
  71. this.internalStore.Enqueue(item);
  72. }
  73. /// <summary>
  74. /// Clear the collection
  75. /// </summary>
  76. public void Clear()
  77. {
  78. this.internalStore = new ConcurrentQueue<T>();
  79. }
  80. }
  81. }