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

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bridge_go

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值