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

后端 未结 9 520
误落风尘
误落风尘 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: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();
    var x = new ConcurrentBag();
    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);
    }
    

提交回复
热议问题