Search code examples
c#concurrency

How to remove all Items from ConcurrentBag?


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


Solution

  • Although it might not completely clear due to a potential race condition, this is sufficient:

    while (!myBag.IsEmpty) 
    {
       myBag.TryTake(out T _);
    }