Search code examples
c#winformsconcurrent-queue

How do I iterate concurrent queue repeatedly?


I am using Winforms and targeting .Net 4.5

I want to iterate concurrent queue for as long as it has items. In my application, the user can add and remove items to the concurrent queue at any point.

Sample code:

ConcurrentQueue<string> cq = new ConcurrentQueue<string>();

cq.Enqueue("First");
cq.Enqueue("Second");
cq.Enqueue("Third");
cq.Enqueue("Fourth");
cq.Enqueue("Fifth");

private void someMethod(string)
{
   //do stuff
}

while (!cq.IsEmpty)
{
   //how do I do the code below in a loop?

   //inner loop starts here 
   someMethod(current cq item);
   //move to the next item
   someMethod(the next cq item);
   //move to the next item
   someMethod(the next cq item);
   . 
   .
   .
   //if last item is reached, start from the top

}

Keep in mind that the application user can add or remove items from the queue at any time, even when the while loop is running.


Solution

  • You should be wrapping the queue in a BlockingCollection (and then not accessing the underlying queue directly) to have a thread safe queue that allows you to wait (block) for an item to become available. Once you have that you can use GetConsumingEnumerable() if you want to loop through items to process, or just call Take explicitly for each item you want.