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
}

Comments

Popular posts from this blog

Tibco Rendezvous (tibrv) C# .Net example

Parse XML to dynamic object in C#