C# 中的线程安全并发集合
.NET Framework 4 引入了 System.Collections.Concurrent 命名空间。这有几个线程安全且可扩展的集合类。这些集合被称为并发集合,因为多个线程可以同时访问。
以下是 C# 中的并发集合 -
| 序号 | 类型和描述 |
|---|---|
| 1 | BlockingCollection<T> 任何类型的阻塞和限界功能。 |
| 2 | ConcurrentDictionary<TKey,TValue> 关键值对字典的线程安全实现。 |
| 3 | ConcurrentQueue<T> 先进先出 (FIFO) 队列的线程安全实现。 |
| 4 | ConcurrentStack<T> 后进先出 (LIFO) 栈的线程安全实现。 |
| 5 | ConcurrentBag<T> 无序元素集合的线程安全实现。 |
| 6 | IProducerConsumerCollection<T> 类型必须实现该接口才能在 BlockingCollection 中使用 |
让我们看看如何使用 ConcurrentStack<T>,它是一个线程安全的后进先出 (LIFO) 集合。
创建一个 ConcurrentStack。
ConcurrentStack<int> s = new ConcurrentStack<int>();
添加元素
s.Push(1); s.Push(2); s.Push(3); s.Push(4); s.Push(5); s.Push(6);
让我们看一个示例
示例
using System;
using System.Collections.Concurrent;
class Demo{
static void Main (){
ConcurrentStack s = new ConcurrentStack();
s.Push(50);
s.Push(100);
s.Push(150);
s.Push(200);
s.Push(250);
s.Push(300);
if (s.IsEmpty){
Console.WriteLine("The stack is empty!");
}
else {
Console.WriteLine("The stack isn't empty");
}
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP