Home >Backend Development >C++ >How Can I Implement a Fixed-Size History Queue Using ConcurrentQueue?
Extending ConcurrentQueue for Fixed-Size History Management
System.Collections.Concurrent.ConcurrentQueue is a robust tool for managing queues in multithreaded environments. However, it doesn't inherently support a fixed-size limitation; older entries aren't automatically removed when the queue is full.
Introducing the FixedSizedQueue Solution
To overcome this limitation, we'll build a FixedSizedQueue
wrapper class. This class enhances the functionality of ConcurrentQueue
to automatically dequeue outdated elements upon new insertions.
Implementation Strategy
FixedSizedQueue
encapsulates a private ConcurrentQueue
instance and a lock object for thread safety. The Enqueue
method checks the queue's Count
. If it exceeds the predefined Limit
, the method acquires the lock, then repeatedly dequeues elements until the Count
is below the Limit
.
Practical Application
To utilize FixedSizedQueue
, initialize it with the desired Limit
:
<code class="language-csharp">FixedSizedQueue<string> urlQueue = new FixedSizedQueue<string>(100);</code>
Adding new URLs (and automatically removing older ones) is straightforward:
<code class="language-csharp">urlQueue.Enqueue("example.com");</code>
Benefits
FixedSizedQueue
offers a streamlined and efficient approach to managing fixed-size historical data. It prioritizes the most recent entries while automatically discarding older ones, ideal for scenarios with limited storage or when tracking a specific number of recent events is crucial.
The above is the detailed content of How Can I Implement a Fixed-Size History Queue Using ConcurrentQueue?. For more information, please follow other related articles on the PHP Chinese website!