Home > Article > Backend Development > Make your collections thread-safe in C#
.NET Framework 4 introduced the System.Collections.Concurrent namespace. It has several thread-safe and extensible collection classes. These collections are called concurrent collections because they can be accessed by multiple threads at the same time.
The following concurrent collection types use lightweight synchronization mechanisms: SpinLock, SpinWait, etc. These are new features in .NET Framework 4.
Let’s look at concurrent collections in C# -
type | describe |
---|---|
Blocking Collection |
Any type of border and blocking functionality. |
Concurrency Dictionary |
Thread-safe implementation of key-value dictionary. |
Concurrent Queue |
Thread-safe implementation of FIFO (first in, first out) queue. |
Concurrency stack |
Thread-safe implementation of LIFO (last in, first out) stack. |
Concurrency package |
Thread-safe implementation of unordered element collection. |
IProducerConsumerCollection |
Interfaces that types must implement to be used in BlockingCollection |
Let's see how to use ConcurrentStack
ConcurrentStack<int> cs = new ConcurrentStack<int>(); cs.Push(95); cs.Push(120); cs.Push(130);
The above is the detailed content of Make your collections thread-safe in C#. For more information, please follow other related articles on the PHP Chinese website!