Home >Backend Development >C++ >How to Implement a Fixed-Sized Queue with Automatic Dequeueing in C#?

How to Implement a Fixed-Sized Queue with Automatic Dequeueing in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-13 11:57:44196browse

How to Implement a Fixed-Sized Queue with Automatic Dequeueing in C#?

Implementing a fixed size queue with automatic dequeue function in C#

In software development, managing limited storage capacity while retaining necessary information is crucial. When working with queues, you often encounter this situation: new data is constantly added, and old data needs to be discarded when the capacity limit is reached. To solve this problem, we provide a solution using the System.Collections class in the ConcurrentQueue<T> namespace.

Implementing a fixed size queue with dequeue function

To create a fixed-size queue with automatic dequeue functionality, we define a wrapper class FixedSizedQueue<T>, which encapsulates a ConcurrentQueue<T>:

internally
<code class="language-csharp">public class FixedSizedQueue<T>
{
    private readonly ConcurrentQueue<T> q = new ConcurrentQueue<T>();
    private readonly 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)) ;
        }
    }
}</code>

Explanation

The

FixedSizedQueue<T> class provides a single method Enqueue for adding elements to a queue. Internally, it checks if the queue's count exceeds the specified Limit. If so, use the lock statement to lock the queue and dequeue elements until the count falls below the limit.

This mechanism ensures that only the required number of elements are always stored in the queue. The oldest elements are automatically removed to accommodate newer elements.

Usage Example

To use the FixedSizedQueue<T> class, create an instance and set the Limit attribute to the highest desired capacity:

<code class="language-csharp">FixedSizedQueue<string> browserHistory = new FixedSizedQueue<string> { Limit = 100 };</code>

Afterwards, just call the Enqueue method to add a new element to the history:

<code class="language-csharp">browserHistory.Enqueue("www.google.com");</code>

As you add more URLs, the oldest URLs are automatically dequeued, maintaining the required capacity of 100 URLs in the history.

The above is the detailed content of How to Implement a Fixed-Sized Queue with Automatic Dequeueing in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn