How to remove a single, specific object from a ConcurrentBag<>?

后端 未结 9 481
误落风尘
误落风尘 2021-02-02 04:34

With the new ConcurrentBag in .NET 4, how do you remove a certain, specific object from it when only TryTake() and TryPeek() are

9条回答
  •  隐瞒了意图╮
    2021-02-02 05:26

    This is my extension class which I am using in my projects. It can a remove single item from ConcurrentBag and can also remove list of items from bag

    public static class ConcurrentBag
    {
        static Object locker = new object();
    
        public static void Clear(this ConcurrentBag bag)
        {
            bag = new ConcurrentBag();
        }
    
    
        public static void Remove(this ConcurrentBag bag, List itemlist)
        {
            try
            {
                lock (locker)
                {
                    List removelist = bag.ToList();
    
                    Parallel.ForEach(itemlist, currentitem => {
                        removelist.Remove(currentitem);
                    });
    
                    bag = new ConcurrentBag();
    
    
                    Parallel.ForEach(removelist, currentitem =>
                    {
                        bag.Add(currentitem);
                    });
                }
    
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
    
        public static void Remove(this ConcurrentBag bag, T removeitem)
        {
            try
            {
                lock (locker)
                {
                    List removelist = bag.ToList();
                    removelist.Remove(removeitem);                
    
                    bag = new ConcurrentBag();
    
                    Parallel.ForEach(removelist, currentitem =>
                    {
                        bag.Add(currentitem);
                    });
                }
    
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
    }
    

提交回复
热议问题