C# yield return not returning an item as expected
        Posted  
        
            by Jiho Han
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Jiho Han
        
        
        
        Published on 2010-03-23T22:51:45Z
        Indexed on 
            2010/03/23
            22:53 UTC
        
        
        Read the original article
        Hit count: 611
        
I have following code:
private void ProcessQueue()
{
    foreach (MessageQueueItem item in GetNextQueuedItem())
        PerformAction(item);
}
private IEnumerable<MessageQueueItem> GetNextQueuedItem()
{
    if (_messageQueue.Count > 0)
        yield return _messageQueue.Dequeue();
}
Initially there is one item in the queue as ProcessQueue is called. During PerformAction, I would add more items to _messageQueue. However, the foreach loop quits after the initial item and does not see the subsequent items added.
I sense that somehow the initial state of the queue is being captured by yield.
Can someone explain what is happening and give a solution?
© Stack Overflow or respective owner