Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all Items from ConcurrentBag?

Tags:

c#

concurrency

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

like image 663
PawanS Avatar asked Mar 21 '11 12:03

PawanS


1 Answers

Update 10/03/2017: As @Lou correctly points out, assignment is atomic. In this instance, creation of the ConcurrentBag will not be atomic, but putting that reference into the variable will be atomic - so locking or Interlocked.Exchange around it is not strictly required.

Some further reading:

reference assignment is atomic so why is Interlocked.Exchange(ref Object, Object) needed?

Is a reference assignment threadsafe?


You could always lock access to the bag itself and create a new instance of it. Items in the bag will then be elligible for GC if nothing else is holding onto them:

lock (something) {     bag = new ConcurrentBag(); } 

Or as Lukazoid points out:

var newBag = new ConcurrentBag(); Interlocked.Exchange<ConcurrentBag>(ref bag, newBag); 

Easy way to bin the contents, however, this assumes that whenever an item wants access it also gets the lock - this could be expensive and might negate the performance tuning that has gone into the ConcurrentBag itself.

If you know that nothing else will access the bag at this time, wing-and-a-prayer it and don't lock :-)

like image 64
Adam Houldsworth Avatar answered Sep 30 '22 02:09

Adam Houldsworth