Sunday, December 13, 2009 11:10 PM
The ConcurrentQueue<T> class doesn't have a Clear() method. Is there a recommended way to clear it?
Tuesday, December 15, 2009 7:09 AMHi Rich2003-
ConcurrentQueue<T>'s implementation is based on a particular lock-free algorithm that doesn't permit atomically clearing of the collection, hence why no Clear method is exposed. As such, you have two primary options. The first is simply to create a new ConcurrentQueue<T> instead of clearing the original, and then swap in the new for the original. The second is to continually remove from the collection until it's empty, e.g. "T ignored; while(cq.TryDequeue(out ignored));". Which you choose is largely dependent on the needs of your application. The former will be faster, but you also run the risk of losing some items you didn't intend to lose (then again, if the whole point is to empty the collection, that might not matter), and it only works if you have access to all of the variables holding references to the queue. The latter is effective, but it runs the risk of running indefinitely if other threads are concurrently appending; it's also more expensive that simply allocating a new queue.
Hope that helps.