System.Collections.Concurrent 命名空間下提供多個線程安全集合類,只要多個線程同時訪問集合,就應使用這些類來代替 System.Collections 和 System.Collections.Generic 命名空間中的相應類型。 但是,不保證通過擴展方法或通過顯式接口實現訪問集合對象是線程安全的,可能需要由調用方進行同步。
一、相關的類
| 類名 | 說明 |
|---|---|
| BlockingCollection
|
為實現 IProducerConsumerCollection
|
| ConcurrentBag
|
表示對象的線程安全的無序集合。 |
| ConcurrentDictionary<TKey,TValue> | 表示可由多個線程同時訪問的鍵/值對的線程安全集合。 |
| ConcurrentQueue
|
表示線程安全的先進先出 (FIFO) 集合。 |
| ConcurrentStack
|
表示線程安全的后進先出 (LIFO) 集合。 |
| OrderablePartitioner
|
表示將可排序數據源拆分為多個分區的特定方式。 |
| Partitioner | 提供針對數組、列表和可枚舉項的常見分區策略。 |
| Partitioner
|
表示將數據源拆分為多個分區的特定方式。 |
二、介紹2個常用的類csharp ConcurrentDictionary 和 csharp ConcurrentQueue
1、ConcurrentDictionary
2、ConcurrentQueue
屬性
| 屬性名 | 說明 |
|---|---|
| Count | 獲取 ConcurrentQueue
|
| IsEmpty | 獲取一個值,該值指示 ConcurrentQueue
|
方法
| 方法名 | 說明 |
|---|---|
| Clear() | 從 ConcurrentQueue
|
| CopyTo(T[], Int32) | 從指定數組索引開始將 ConcurrentQueue
|
| Enqueue(T) | 將對象添加到 ConcurrentQueue
|
| Equals(Object) | 確定指定對象是否等於當前對象。 (繼承自 Object) |
| GetEnumerator() | 返回循環訪問 ConcurrentQueue
|
| GetHashCode() | 作為默認哈希函數。 (繼承自 Object) |
| GetType() | 獲取當前實例的 Type。 (繼承自 Object) |
| MemberwiseClone() | 創建當前 Object 的淺表副本。 (繼承自 Object) |
| ToArray() | 將 ConcurrentQueue
|
| ToString() | 返回表示當前對象的字符串。 (繼承自 Object) |
| TryDequeue(T) | 嘗試移除並返回並發隊列開頭處的對象。 |
| TryPeek(T) | 嘗試返回 ConcurrentQueue
|
簡單應用
更新中
參考文檔:
1.微軟官方文檔
