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-06-22

1 千次觀看

助力您的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.