Thursday, 4 April 2013

C# ConcurrentQueue with limited number of items

public class LimitedConcurrentQueue<T> : ConcurrentQueue<T>
{
  public int Size { get; private set; }
 
  public LimitedConcurrentQueue(int size)
  {
    Size = size;
  }
 
  public new void Enqueue(T obj)
  {
    base.Enqueue(obj);
    lock (this)
    {
      while (base.Count > Size)
      {
        T outObj;
        base.TryDequeue(out outObj);
      }
    }
  }
}
 
[Test]
public void TestLimitedConcurrentQueue()
{
  var queue = new LimitedConcurrentQueue<int>(3);
  queue.Enqueue(1);
  queue.Enqueue(2);
  queue.Enqueue(3);
 
  Console.WriteLine(string.Join(",", queue.ToArray()));
  //gives 1,2,3
 
  queue.Enqueue(4);
 
  Console.WriteLine(string.Join(",", queue.ToArray()));
  //gives 2,3,4
}

No comments:

Post a Comment