jassuncao
jassuncao

Reputation: 4777

Collections optimized for concurrency in .Net

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.

Upvotes: 1

Views: 280

Answers (3)

Quibblesome
Quibblesome

Reputation: 25429

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.

Upvotes: 1

Tamas Czinege
Tamas Czinege

Reputation: 121414

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.

Upvotes: 0

Frederik Gheysels
Frederik Gheysels

Reputation: 56964

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

Upvotes: 3

Related Questions