Home > Backend Development > C#.Net Tutorial > Make your collections thread-safe in C#

Make your collections thread-safe in C#

王林
Release: 2023-08-27 22:13:02
forward
737 people have browsed it

在 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);
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template