C#線程安全的集合


ConcurrentBag   集合

表示對象的線程安全的無序集合。


static void Main(string[] args)
{
    ConcurrentBag<int> thList = new ConcurrentBag<int>();
    Parallel.For(0, 100000, a =>
      {
          thList.Add(a);
      });
    thList.TryPeek(out int result1);   //獲取末尾的值
    Console.WriteLine(string.Format("Count:{0} Result:{1}", thList.Count, result1));

    thList.TryTake(out int result2);  //刪除並獲取末尾的值
    Console.WriteLine(string.Format("Count:{0} Result:{1}", thList.Count, result2));
    Console.ReadKey();
}

注:若是使用List<int>,在並行添加數據時要么會拋異常要么集合中的個數不對。

PS:ConcurrentBag<T>不能像List<T>一樣輕易獲取任何索引處的值和刪除任意一個值。 若要使用獲取和刪除,請使用ConcurrentDictionary。

ConcurrentDictionary 字典

static void Main(string[] args)
{
    ConcurrentDictionary<int, int> thDict = new ConcurrentDictionary<int, int>();
    Parallel.For(0, 10, a =>
      {
          bool isOK = thDict.TryAdd(a, a);
          if (thDict.ContainsKey(4))
          {
              thDict[4] = 400;
          }
      });
    Console.WriteLine(string.Format("Count:{0} Values:{1}", thDict.Count, string.Join(",", thDict.Values)));

    thDict.TryRemove(3, out int value);
    Console.WriteLine(string.Format("Count:{0} value:{1} Values:{2}", thDict.Count, value, string.Join(",", thDict.Values)));

    Console.ReadKey();
}

 ConcurrentQueue  隊

表示線程安全的先進先出 (FIFO) 集合。 

static void Main(string[] args)
{
    ConcurrentQueue<int> thQueue = new ConcurrentQueue<int>();
    Parallel.For(0, 10, a =>
    {
        thQueue.Enqueue(a);
    });
    thQueue.TryPeek(out int result1);   //獲取開頭處的對象
    thQueue.TryDequeue(out int result2);  //獲取開頭處的對象並將其移除
    Console.ReadKey();
}

ConcurrentStack  棧

表示線程安全的后進先出 (LIFO) 集合。 

static void Main(string[] args)
{
    ConcurrentStack<int> thQueue = new ConcurrentStack<int>();
    Parallel.For(0, 10, a =>
    {
        thQueue.Push(a);
    });
    thQueue.TryPeek(out int result1);   //獲取頂部的對象
    thQueue.TryPop(out int result2);  //獲取頂部的對象並將其移除
    Console.ReadKey();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM