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