C# 中的執行緒安全併發集合


.NET Framework 4 引入了 System.Collections.Concurrent 名稱空間。它有若干個執行緒安全且可擴充套件的集合類。這些集合稱為併發集合,因為可以由多個執行緒同時訪問它們。

以下是在 C# 中的併發集合 −

序號型別 & 說明
1BlockingCollection<T>
對任何型別的限定和阻斷功能。
2ConcurrentDictionary<TKey,TValue>
鍵值對字典的執行緒安全實現。
3ConcurrentQueue<T>
FIFO(先進先出)佇列的執行緒安全實現。
4ConcurrentStack<T>
LIFO(後進先出)堆疊的執行緒安全實現。
5ConcurrentBag<T>
元素無序集合的執行緒安全實現。
6IProducerConsumerCollection<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");
      }
   }
}

更新於:2020 年 6 月 22 日

1000+ 瀏覽量

開啟您的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.