Search code examples
c#concurrencyqueuefifoconcurrent-queue

Fixed size queue which automatically dequeues old values upon new enqueues


I'm using ConcurrentQueue<T> for a shared data structure which purpose is holding the last N objects passed to it (kind of history).

Assume we have a browser and we want to have the last 100 browsed Urls. I want a queue which automatically drop (dequeue) the oldest (first) entry upon new entry insertion (enqueue) when the capacity gets full (100 addresses in history).

How can I accomplish that using System.Collections?


Solution

  • I would write a wrapper class that on Enqueue would check the Count and then Dequeue when the count exceeds the limit.

     public class FixedSizedQueue<T>
     {
         readonly ConcurrentQueue<T> q = new ConcurrentQueue<T>();
         private object lockObject = new object();
    
         public int Limit { get; set; }
         public void Enqueue(T obj)
         {
            q.Enqueue(obj);
            lock (lockObject)
            {
               T overflow;
               while (q.Count > Limit && q.TryDequeue(out overflow)) ;
            }
         }
     }