Home > Backend Development > C++ > How to Maintain a Bounded History Using a Concurrent Queue in C#?

How to Maintain a Bounded History Using a Concurrent Queue in C#?

Patricia Arquette
Release: 2025-01-13 09:01:43
Original
364 people have browsed it

How to Maintain a Bounded History Using a Concurrent Queue in C#?

Using System.Collections.Concurrent for a Fixed-Size History

Imagine needing a data structure to track recent history, like browser URLs. System.Collections.Concurrent.ConcurrentQueue is a good choice, but we need to limit its size.

This example demonstrates a FixedSizedQueue<T> class that wraps ConcurrentQueue to manage a bounded history:

<code class="language-csharp">public class FixedSizedQueue<T>
{
    private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
    private readonly object _lock = new object();
    public int Limit { get; set; }

    public void Enqueue(T item)
    {
        _queue.Enqueue(item);

        lock (_lock)
        {
            T overflow;
            while (_queue.Count > Limit && _queue.TryDequeue(out overflow)) { }
        }
    }

    // Add other methods like Dequeue, Count, etc., as needed.
}</code>
Copy after login

The Limit property defines the maximum queue size. Enqueue adds an item; if the limit is exceeded, it uses a lock to safely remove older items until the size is within the limit. This keeps only the most recent entries. You would extend this class to include other methods like Dequeue, Count, etc., as required by your application.

The above is the detailed content of How to Maintain a Bounded History Using a Concurrent Queue in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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