I have a scenario where I need to remove an item for the queue as soon as been processed. I understand I cannot remove an item from a collection whilst in loop but was wond
foreach as a reasonable way to iterate through the queue when you are not removing items
When you want to remove and process items, the thread-safe, proper way is just remove them one at a time and process them after they have been removed.
One way is this
// the non-thread safe way
//
while (queueList.Count > 0)
{
Order orderItem = queueList.Dequeue();
Save(orderItem);
Console.WriteLine("Id :{0} Name {1} ", orderItem.Id, orderItem.Name);
}
It's possible for the number of items in the queue to change between queueList.Count and queueList.Dequeue(), so to be thread safe, you have to just use Dequeue, but Dequeue will throw when the queue is empty, so you have to use an exception handler.
// the thread safe way.
//
while (true)
{
Order orderItem = NULL;
try { orderItem = queueList.Dequeue(); } catch { break; }
if (null != OrderItem)
{
Save(orderItem);
Console.WriteLine("Id :{0} Name {1} ", orderItem.Id, orderItem.Name);
}
}