How to remove all Items from ConcurrentBag?

前端 未结 6 1145
猫巷女王i
猫巷女王i 2021-01-31 13:30

How to clear the ConcurrentBag? it don\'t have any method like Clear or RemoveAll...

6条回答
  •  旧时难觅i
    2021-01-31 13:46

    The selected answer is kind of, well, a workaround, so I'm adding my own workaround.

    My solution was to look at all the available collections in the System.Collections.Concurrent namespace to find one where it was trivial to clear all elements from the collection.

    The ConcurrentStack class has a Clear() method which removes all elements from the collection. In fact, it's the only collection in the namespace (currently) that does. Yes, you have to Push(T element) instead of Add(T element), but frankly that's worth the time saved.

提交回复
热议问题