In the scene where multi -threaded access queues are accessed at the same time, the control queue size is critical to prevent the infinite growth of the queue. This article discusses the method of creating a custom blocking queue in the .NET.
A simple solution is to use the collection as the basis of the queue, and use
(_fullevent) to block the additional thread when the queue reaches the specified maximum (maxsize). When removing the project, a _fullevent signal is issued to allow the team.
AutoResetEvent
However, due to insufficient synchronization, the safety of this implementation is worrying. The improvement method is to use the standardized queue type and use the synchronous element to display the management obstruction.
The following code shows the implementation of the improved:
This realization provides a mechanism that provides a safe and efficient queue size by using a built -in synchronization structure. In addition, it also includes the function of closing the queue elegantly, allowing the reader to exit cleanly.
<code class="language-csharp">class SizeQueue<T> { private readonly Queue<T> queue = new Queue<T>(); private readonly int maxSize; public SizeQueue(int maxSize) { this.maxSize = maxSize; } public void Enqueue(T item) { lock (queue) { while (queue.Count >= maxSize) { Monitor.Wait(queue); } queue.Enqueue(item); if (queue.Count == 1) { // 唤醒任何被阻塞的出队操作 Monitor.PulseAll(queue); } } } public T Dequeue() { lock (queue) { while (queue.Count == 0) { Monitor.Wait(queue); } T item = queue.Dequeue(); if (queue.Count == maxSize - 1) { // 唤醒任何被阻塞的入队操作 Monitor.PulseAll(queue); } return item; } } }</code>
The above is the detailed content of How to Implement a Thread-Safe Blocking Queue with Size Limits in .NET?. For more information, please follow other related articles on the PHP Chinese website!