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?
Collections. Concurrent namespace. This has several collection classes that are thread-safe and scalable. These collections are called concurrent collections because they can be accessed by multiple threads at a time.
A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
NET class libraries are not thread safe by default. Avoid providing static methods that alter static state. In common server scenarios, static state is shared across requests, which means multiple threads can execute that code at the same time. This opens up the possibility of threading bugs.
ConcurrentDictionary<TKey,T>Concurrent dictionary is 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.
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With