Update 03/10/2017: As @Lou correctly points out, the assignment is atomic. In this case, creating a ConcurrentBag will not be atomic, but including this link in the variable will be atomic - therefore, locking or Interlocked.Exchange around it is strictly not required.
Further reading:
Link assignment is atomic, so why do I need Interlocked.Exchange (ref Object, Object)?
Is the referential assignment thread safe?
You can always block access to the bag itself and create a new copy. Then the items in the bag will be available for GC, if nothing else holds on to them:
lock (something) { bag = new ConcurrentBag(); }
Or, as Lucasoid points out:
var newBag = new ConcurrentBag(); Interlocked.Exchange<ConcurrentBag>(ref bag, newBag);
An easy way to unload the content, however, this assumes that whenever the element wants to access, it also gets a lock - this can be expensive and may negate the performance tuning that got into the ConcurrentBag itself.
If you know that at this time nothing else will be available in the bag, it will be closed and will not block :-)
Adam Houldsworth Mar 21 '11 at 12:39 2011-03-21 12:39
source share