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)
!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With