Home > Backend Development > C++ > How to Design a Thread-Safe Blocking Queue in .NET?

How to Design a Thread-Safe Blocking Queue in .NET?

DDD
Release: 2025-01-30 04:51:12
Original
214 people have browsed it

How to Design a Thread-Safe Blocking Queue in .NET?

Construct a thread security blocking queue in the .NET

In multi -threaded environment, when multiple threads operate the same queue, efficient queue management is essential. This article discusses how to create a blocking queue in the .NET to meet this demand.

The limitations of existing implementation

The code fragment provided in the question shows the basic implementation of a blocking queue. However, it lacks appropriate synchronization mechanisms and may lead to thread security issues.

Improvement method

In order to solve the limitations of the original implementation, please consider the following improved version:

In this improved version, the
<code class="language-csharp">class SizeQueue<T>
{
    private readonly Queue<T> queue = new Queue<T>();
    private readonly int maxSize;
    private bool closing; // 添加关闭标志

    public SizeQueue(int maxSize) { this.maxSize = maxSize; }

    public void Enqueue(T item)
    {
        lock (queue)
        {
            while (queue.Count >= maxSize && !closing) // 检查关闭标志
            {
                Monitor.Wait(queue);
            }
            if(closing) return; // 如果队列已关闭,则直接返回
            queue.Enqueue(item);
            if (queue.Count == 1)
            {
                Monitor.PulseAll(queue);
            }
        }
    }

    public T Dequeue()
    {
        lock (queue)
        {
            while (queue.Count == 0 && !closing) // 检查关闭标志
            {
                Monitor.Wait(queue);
            }
            if(closing && queue.Count == 0) throw new InvalidOperationException("Queue is closed and empty."); // 队列关闭且为空
            T item = queue.Dequeue();
            if (queue.Count == maxSize - 1)
            {
                Monitor.PulseAll(queue);
            }
            return item;
        }
    }

    public void Close()
    {
        lock (queue)
        {
            closing = true;
            Monitor.PulseAll(queue);
        }
    }

    public bool TryDequeue(out T value)
    {
        lock (queue)
        {
            while (queue.Count == 0)
            {
                if (closing)
                {
                    value = default(T);
                    return false;
                }
                Monitor.Wait(queue);
            }
            value = queue.Dequeue();
            if (queue.Count == maxSize - 1)
            {
                Monitor.PulseAll(queue);
            }
            return true;
        }
    }
}</code>
Copy after login
sentence protection queue operation to ensure thread safety.

Class is used to block and lift the blocking thread according to the status of the queue. In addition, the logo and lock methods are added to the elegant closure of the queue, and the Monitor method is used to handle the queue as empty. closing Close() further consideration TryDequeue()

For actual applications, it may need to deal with the situation where the queue is closed or the need for elegance is needed. For this reason, the code can be modified as follows (as shown above).

These enhanced functions allow the reading thread in an orderly manner when the queue is closed. The improved code increases the check of the queue closure, and processes the situation of the queue closure and empty, avoiding abnormalities.

The above is the detailed content of How to Design a Thread-Safe Blocking Queue in .NET?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template