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)
!