3

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.

TH Todorov
  • 1,129
  • 11
  • 26
  • What happens when let's say your concurrentqueue is empty (all items are consumed) and new item is added? Should it be consumed automatically by your requirements? – Michael May 14 '15 at 20:55
  • I haven't even thought that far, but yes. I can probably solve that with a timer that checks if the collection has items and if it does, start the loop if it is not already running. – TH Todorov May 14 '15 at 21:44

1 Answers1

2

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.

Servy
  • 202,030
  • 26
  • 332
  • 449