Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safe collections in .NET

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?

like image 873
ripper234 Avatar asked Jun 05 '10 12:06

ripper234


People also ask

Are collections thread-safe in C#?

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.

What are thread-safe collections?

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.

Is .NET thread-safe?

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.

Which of the following C# collections are thread-safe?

ConcurrentDictionary<TKey,T>Concurrent dictionary is thread-safe collection.


1 Answers

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"); } 
like image 197
dtb Avatar answered Oct 04 '22 20:10

dtb