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

How to Implement a Fixed-Size Queue with Automatic Dequeuing in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-13 08:50:47833browse

How to Implement a Fixed-Size Queue with Automatic Dequeuing in C#?

Creating a Fixed-Size Queue in C# with Automatic Removal of Older Items

This article addresses the creation of a data structure that maintains a limited history of objects, automatically discarding the oldest entries when the maximum size is reached. We'll build this queue using the System.Collections namespace.

Solution:

The solution uses a wrapper class, FixedSizedQueue<T>, around ConcurrentQueue<T>. The Enqueue method in this wrapper checks the queue's size. If the queue is full (defined by the Limit property), the oldest item is removed via Dequeue to accommodate the new item.

Here's the C# code for the FixedSizedQueue<T> class:

<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; }

    public void Enqueue(T obj)
    {
        queue.Enqueue(obj);
        lock (lockObject)
        {
            T overflow;
            while (queue.Count > Limit && queue.TryDequeue(out overflow)) ;
        }
    }
}</code>

Using FixedSizedQueue<T> ensures a fixed-size history, with automatic removal of older items upon reaching the capacity limit.

The above is the detailed content of How to Implement a Fixed-Size Queue with Automatic Dequeuing 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