Home  >  Article  >  Backend Development  >  Make your collections thread-safe in C#

Make your collections thread-safe in C#

王林
王林forward
2023-08-27 22:13:02715browse

在 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, which is a thread-safe last-in-first-out (LIFO) collection -

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Naming conventions in C#Next article:Naming conventions in C#