net 多线程 学习 32 线程安全的集合

ConcurrentBag

ConcurrentBag 就是利用线程槽来分摊Bag中的所有数据。

ConcurrentBag的所有数据都是防止在多个插入线程的槽位中,每个线程一个子集


using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConCurrentBagDemo
{
    class Program
    {
        // Demonstrates:
        //      ConcurrentBag<T>.Add()
        //      ConcurrentBag<T>.IsEmpty
        //      ConcurrentBag<T>.TryTake()
        //      ConcurrentBag<T>.TryPeek()
        static void Main()
        {
            // Construct and populate the ConcurrentBag
            ConcurrentBag<int> cb = new ConcurrentBag<int>();
            cb.Add(1);
            cb.Add(2);
            cb.Add(3);

            // Consume the items in the bag
            int item;
            while (!cb.IsEmpty)
            {
                if (cb.TryTake(out item))
                    Console.WriteLine(item);
                else
                    Console.WriteLine("TryTake failed for non-empty bag");
            }

            // Bag should be empty at this point
            if (cb.TryPeek(out item))
                Console.WriteLine("TryPeek succeeded for empty bag!");

            Console.ReadKey();
        }

    }
}


ConcurrentStack

线程安全的Stack是使用链表的形式,而同步版本是用 数组 实现的。。。 线程安全的Stack是使用Interlocked来实现线程安全。。 而没有使用 内核锁

ConcurrentQueue

同步版本使用 数组

ConcurrentDictionary


作者:spike

分类: Net

创作时间:2023-06-25

更新时间:2024-12-09

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1