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