Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through list in a thread continually as it receives new elements

I'm really not sure how to approach this, but I am subscribing to events fired within a custom class and ideally I wish to queue them and handle them first in first out as they come in. I am aware of Queue<T> and I think I should use this? but my question is in the event handler when my message is received, would I simply Enqueue() to the queue there, and if so, then how can the queue be crunched through as new items are added?

I was considering calling a method in the constructor which performs something like (hold on to your hats):

while (true)
{
  foreach (var item in myQueue)
  {
    // process
    myQueue.Dequeue();
  }
}

Surely there must be a more elegant way to do this? This should effectively hit myQueue and iterate as it contains elements and do what I want though. What would performance be like? I can spawn this on a separate thread to avoid any thread blocking, I just really have a had time accepting while (true)!

like image 693
GONeale Avatar asked Dec 23 '22 12:12

GONeale


1 Answers

This is a classic producer/consumer problem. A quick web search reveals http://msdn.microsoft.com/en-us/library/yy12yx1f(VS.80,loband).aspx, which covers this exactly.

You don't want to do a while(true) loop since your thread will be burning 100% of the CPU, even when there is no work for it do, potentially starving other threads in the system.

like image 139
Michael Avatar answered Dec 28 '22 07:12

Michael