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

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

    The ConcurrentBag is great to handle a List where you can add items and enumerate from many thread, then eventually throw it away as its name is suggesting :)

    As Mark Byers told, you can re-build a new ConcurrentBag that does not contains the item you wish to remove, but you have to protect this against multiple threads hits using a lock. This is a one-liner:

    myBag = new ConcurrentBag(myBag.Except(new[] { removedEntry }));
    

    This works, and match the spirit in which the ConcurrentBag has been designed for.

提交回复
热议问题