views:

152

answers:

3

In the java world there is a set of classes optimized for concurrent tasks. I assume there is something similar in .Net, but after a quick search in MSDN I couldn't find anything. I was looking for a queue with fairness policy to be used in consumer/producer situations.

Thanks.

+3  A: 

The Parallels Library for .NET contains some thread-safe collections.

One of them is a ConcurrentQueue<T>

http://blogs.msdn.com/pfxteam/archive/2008/08/12/8852005.aspx

Frederik Gheysels
A: 

The non-generic .NET collections (System.Collections namespace) can all do this. I've nicked the following snippet from MSDN Queue.SyncRoot page:

Queue myCollection = new Queue();

lock(myCollection.SyncRoot)
{
   foreach (Object item in myCollection)
   {
      // Insert your code here.
   }
}

Or you can just create a synchronized wrapper right away:

Queue mySyncCollection = Queue.Synchronized(myCollection);
// No locks required

Unfortunately this is not possible to do with the generic collections so probably you will have to write your own wrappers / extension methods if you want to use generic collections.

DrJokepu
Your synchronized statement locks on the instance of the class which can lead to deadlocks and other bad things!
Henrik
Henrik: Are you sure? This is not like, locking on the instance of the collection. That's the whole point. As I've said, I've stolen the examples from MSDN anyway.
DrJokepu
+1  A: 

Surely an oxymoron? Collections that are thread-safe will probably aquire more locks than required. To optimise one usually defines the locks in a higher location.

Quibblesome