How can I modify a queue collection in a loop?

前端 未结 3 1073
离开以前
离开以前 2020-12-19 01:49

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

3条回答
  •  庸人自扰
    2020-12-19 02:12

    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);
        }
    }
    

提交回复
热议问题