Home >Backend Development >C++ >How Can I Implement a Fixed-Size Queue with Automatic Dequeueing in C#?
Creating a C# Fixed-Size Queue with Automatic Dequeueing
Many applications need a data structure that holds a fixed number of items, removing the oldest when it's full. This is useful for tracking recent events or maintaining a history. Imagine a web browser needing to store the last 100 URLs visited. While ConcurrentQueue<T>
could work, managing the dequeuing manually is inefficient. A custom wrapper class provides a cleaner solution.
The FixedSizedQueue<T>
Class
This class wraps a ConcurrentQueue<T>
, handling both enqueueing and dequeueing to maintain a set size. The class definition includes:
<code class="language-csharp">public class FixedSizedQueue<T> { private readonly ConcurrentQueue<T> queue = new ConcurrentQueue<T>(); private readonly object lockObject = new object(); public int Limit { get; set; } // ... other methods }</code>
The Enqueue
Method
The Enqueue
method adds items. If the queue exceeds the limit, it removes older items:
<code class="language-csharp">public void Enqueue(T item) { queue.Enqueue(item); lock (lockObject) { T overflow; while (queue.Count > Limit && queue.TryDequeue(out overflow)) ; } }</code>
Using FixedSizedQueue<T>
To use the class, create an instance and set the limit:
<code class="language-csharp">var urlHistory = new FixedSizedQueue<string> { Limit = 100 };</code>
Adding items automatically maintains the size:
<code class="language-csharp">urlHistory.Enqueue("www.google.com"); // Enqueues the URL urlHistory.Enqueue("www.microsoft.com"); // The oldest URL is automatically dequeued</code>
This approach provides a more elegant and efficient way to manage fixed-size queues in C#.
The above is the detailed content of How Can I Implement a Fixed-Size Queue with Automatic Dequeueing in C#?. For more information, please follow other related articles on the PHP Chinese website!