Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safe blocking queue implementation on .NET

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.

like image 457
Shrike Avatar asked Apr 29 '09 09:04

Shrike


People also ask

Is blocking queue thread-safe?

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.

Is queue in C# thread-safe?

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.

How is blocking queue implemented?

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.

What is a BlockingCollection C#?

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.


2 Answers

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.

like image 59
Sam Harwell Avatar answered Oct 28 '22 03:10

Sam Harwell


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.

like image 28
Marc Gravell Avatar answered Oct 28 '22 03:10

Marc Gravell