Home > Backend Development > C++ > How Can I Implement a Fixed-Size Queue with Automatic Dequeueing in C#?

How Can I Implement a Fixed-Size Queue with Automatic Dequeueing in C#?

Barbara Streisand
Release: 2025-01-13 08:21:43
Original
527 people have browsed it

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:

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
}
Copy after login

The Enqueue Method

The Enqueue method adds items. If the queue exceeds the limit, it removes older items:

public void Enqueue(T item)
{
    queue.Enqueue(item);
    lock (lockObject)
    {
        T overflow;
        while (queue.Count > Limit && queue.TryDequeue(out overflow)) ;
    }
}
Copy after login

Using FixedSizedQueue<T>

To use the class, create an instance and set the limit:

var urlHistory = new FixedSizedQueue<string> { Limit = 100 };
Copy after login

Adding items automatically maintains the size:

urlHistory.Enqueue("www.google.com");  // Enqueues the URL
urlHistory.Enqueue("www.microsoft.com"); // The oldest URL is automatically dequeued
Copy after login

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!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template