Construct a thread security blocking queue in the .NET
The limitations of existing implementation
Improvement method
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>
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()
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!