none
Clear a ConcurrentQueue?

    Question

  • The ConcurrentQueue<T> class doesn't have a Clear() method. Is there a recommended way to clear it?

    Sunday, December 13, 2009 11:10 PM

Answers

  • Hi 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.
    Tuesday, December 15, 2009 7:09 AM

All replies

  • Hi 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.
    Tuesday, December 15, 2009 7:09 AM
  • Usefull extension:

    internal static class ConcurrentQueueExtensions
    {
    	public static void Clear<T>(this ConcurrentQueue<T> queue)
    	{
    		T item;
    		while (queue.TryDequeue(out item))
    		{
    			// do nothing
    		}
    	}
    }

    Wednesday, June 12, 2013 9:27 PM
  • Can also use the IsEmpty property

    Public Sub ClearQueue() 
       Dim item As Integer
       While (Not myQ.IsEmpty)
          myQ.TryDequeue(item)
       End While
    End Sub


    Wednesday, January 24, 2018 5:08 PM