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

后端 未结 9 482
误落风尘
误落风尘 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:13

    You can't. Its a bag, it isn't ordered. When you put it back, you'll just get stuck in an endless loop.

    You want a Set. You can emulate one with ConcurrentDictionary. Or a HashSet that you protect yourself with a lock.

    0 讨论(0)
  • 2021-02-02 05:14

    As you mention, TryTake() is the only option. This is also the example on MSDN. Reflector shows no other hidden internal methods of interest either.

    0 讨论(0)
  • 2021-02-02 05:16

    how about:

    bag.Where(x => x == item).Take(1);
    

    It works, I'm not sure how efficiently...

    0 讨论(0)
  • 2021-02-02 05:20
    public static ConcurrentBag<String> RemoveItemFromConcurrentBag(ConcurrentBag<String> Array, String Item)
    {
        var Temp=new ConcurrentBag<String>();
        Parallel.ForEach(Array, Line => 
        {
           if (Line != Item) Temp.Add(Line);
        });
        return Temp;
    }
    
    0 讨论(0)
  • 2021-02-02 05:21

    Mark is correct in that the ConcurrentDictionary is will work in the way you are wanting. If you wish to still use a ConcurrentBag the following, not efficient mind you, will get you there.

    var stringToMatch = "test";
    var temp = new List<string>();
    var x = new ConcurrentBag<string>();
    for (int i = 0; i < 10; i++)
    {
        x.Add(string.Format("adding{0}", i));
    }
    string y;
    while (!x.IsEmpty)
    {
        x.TryTake(out y);
        if(string.Equals(y, stringToMatch, StringComparison.CurrentCultureIgnoreCase))
        {
             break;
        }
        temp.Add(y);
    }
    foreach (var item in temp)
    {
         x.Add(item);
    }
    
    0 讨论(0)
  • 2021-02-02 05:23

    The short answer: you can't do it in an easy way.

    The ConcurrentBag keeps a thread local queue for each thread and it only looks at other threads' queues once its own queue becomes empty. If you remove an item and put it back then the next item you remove may be the same item again. There is no guarantee that repeatedly removing items and putting them back will allow you to iterate over the all the items.

    Two alternatives for you:

    • Remove all items and remember them, until you find the one you want to remove, then put the others back afterwards. Note that if two threads try to do this simultaneously you will have problems.
    • Use a more suitable data structure such as ConcurrentDictionary.
    0 讨论(0)
提交回复
热议问题