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 wondering if something
could be done with the Enumerator etc…
This is just a basic example throwing an error
“Collection was modified after the enumerator was instantiated.”
Any suggestions? Thanks a lot!!!
Code is as follows:
class Program
{
static void Main()
{
Queue<Order> queueList = GetQueueList();
foreach (Order orderItem in queueList)
{
Save(orderItem);
Console.WriteLine("Id :{0} Name {1} ", orderItem.Id, orderItem.Name);
queueList.Dequeue();
}
Console.Read();
}
private static void Save(Order orderItem)
{
//we are pretending to save or do something.
}
private static Queue<Order>GetQueueList()
{
Queue<Order> orderQueue = new Queue<Order>();
orderQueue.Enqueue(new Order { Id = 1, Name = "Order 1" });
orderQueue.Enqueue(new Order { Id = 1, Name = "Order 2" });
orderQueue.Enqueue(new Order { Id = 2, Name = "Order 3" });
orderQueue.Enqueue(new Order { Id = 3, Name = "Order 4" });
orderQueue.Enqueue(new Order { Id = 4, Name = "Order 5" });
return orderQueue;
}
}
public class Order
{
public int Id { get; set; }
public string Name { get; set; }
}
Change your foreach to:
Edit:
To reprocess if save fails do something like:
Edit:
John K mentions thread safety which is a valid concern if you have multiple threads accessing the same
Queue. See http://ccutilities.codeplex.com/SourceControl/changeset/view/40529#678487 for aThreadSafeQueueclass that covers simple thread safety issues.Edit: Here’s the thread safety example I keep pointing everyone to 🙂
Here’s an example of the thread safety issues mentioned. As shown the default
Queuecan “miss” items while still decreasing the count.Updated: To better represent the problem. I never add a null item to the
Queuebut the standardQueue.Dequeue()returns several null values. This alone would be fine but in doing so a valid item is removed from the internal collection and theCountdecreases. It’s a safe assumption, in this specific example, that everynullitem returned from aQueue.Dequeue()operation represents a valid item that was never processed.