Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 596
TH Todorov Avatar asked May 07 '26 08:05

TH Todorov


1 Answers

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.

like image 112
Servy Avatar answered May 09 '26 23:05

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!