views:

146

answers:

3

What is the standard nowadays when one needs a thread safe collection (e.g. Set). Do I synchronize it myself, or is there an inherently thread safe collection?

+11  A: 

The .NET 4.0 Framework introduces several thread-safe collections in the System.Collections.Concurrent Namespace:

ConcurrentBag<T>
      Represents a thread-safe, unordered collection of objects.

ConcurrentDictionary<TKey, TValue>
    Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.

ConcurrentQueue<T>
    Represents a thread-safe first in-first out (FIFO) collection.

ConcurrentStack<T>
    Represents a thread-safe last in-first out (LIFO) collection.


Other collections in the .NET Framework are not thread-safe by default and need to be locked for each operation:

lock (mySet)
{
    mySet.Add("Hello World");
}
dtb
+1  A: 

.NET 4 provides a set of thread-safe collections under System.Collections.Concurrent

Kai Wang
+3  A: 

Pre .net 4.0 most collections in .Net are not thread safe. You'll have to do some work yourself to handle the synchronization: http://msdn.microsoft.com/en-us/library/573ths2x.aspx

Quote from article:

Collections classes can be made thread safe using any of the following methods:

Create a thread-safe wrapper using the Synchronized method, and access the collection exclusively through that wrapper.

If the class does not have a Synchronized method, derive from the class and implement a Synchronized method using the SyncRoot property.

Use a locking mechanism, such as the lock statement in C# (SyncLock in Visual Basic), on the SyncRoot property when accessing the collection.

Sync Root Property
Lock Statement

Object thisLock = new Object();
......
lock (thisLock)
{
    // Critical code section
}

In .net 4.0 the introduced the System.Collections.Concurrent namespace

Blocking Collection
Concurrent Bag
Concurrent Queue
Concurrent Dictionary
Ordable Partitioner
Partitioner
Partitioner T

Kevin
The object you are locking on should be an instance variable, otherwise it doesn't make sense because you are always locking on a new reference.
Femaref
That is true. This is just an example that was on the MSDN page on how the Lock code is used.
Kevin