C#线程安全的集合

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:49   2391   0

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();
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP