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?
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.
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"); }
1.4m articles
1.4m replys
5 comments
56.9k users