I'm looking for an implementation of thread-safe blocking queue for .NET. By "thread-safe blocking queue" I mean: - thread-safe access to a queue where Dequeue method call blocks a thread untill other thread puts (Enqueue) some value.
By the moment I'v found this one: http://www.eggheadcafe.com/articles/20060414.asp (But it's for .NET 1.1).
Could someone comment/criticize correctness of this implementation. Or suggest some another one. Thanks in advance.
BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.
Queue class also provides FIFO data structure but it is not safe to use with multi-threading environment. To provide thread-safety, we have to implement locking around Queue methods which is always error prone.
Put() Implementation in Blocking Queue This implementation is very similar to enQueue() method. Once the capacity is reached, the thread is blocked or else it's a simple enQueue operation using LinkedList. Once the element is queued, we notify in case other waiting threads are blocked due to an empty queue.
C# C# BlockingCollection is a collection class which ensures thread-safety. Multiple threads can add and remove objects in BlockingCollection concurrently. It implements the producer-consumer pattern. In this pattern, there are two threads one is called producer and other is called consumer.
For the reference, .NET 4 introduces the System.Collections.Concurrent.BlockingCollection<T>
type to address this. For non-blocking queue, you can use System.Collections.Concurrent.ConcurrentQueue<T>
. Note that ConcurrentQueue<T>
would likely be used as the underlying datastore for the BlockingCollection<T>
for the OP's usage.
How about this one Creating a blocking Queue in .NET?
If you need it for .NET 1.1 (I wasn't sure from the question), just drop the generics and replace T
with object
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With