C# yield return not returning an item as expected
- by Jiho Han
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?