C# 收益率返回未按预期返回项目
我有以下代码:
private void ProcessQueue()
{
foreach (MessageQueueItem item in GetNextQueuedItem())
PerformAction(item);
}
private IEnumerable<MessageQueueItem> GetNextQueuedItem()
{
if (_messageQueue.Count > 0)
yield return _messageQueue.Dequeue();
}
最初,当调用 ProcessQueue 时,队列中有一项。 在 PerformAction 期间,我会向 _messageQueue 添加更多项目。但是,foreach 循环在初始项之后退出,并且看不到添加的后续项。
我感觉到队列的初始状态以某种方式被产量捕获。
有人可以解释发生了什么并给出解决方案吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的程序完全按照您的指示执行操作:如果
Count > 则生成一项。 0
- 否则产生零项。要返回项目直到队列变空,请尝试:
Your program does exactly what you instructed to do: it yields one item if
Count > 0
- and yields zero items otherwise.To return items until the queue becomes empty, try:
yield return
实际上暂停执行并执行假返回(它产生一个值),直到请求下一个。在这种情况下,会发生的情况是检查计数是否 > 0,然后产生下一个值。当请求下一个时,您的 if 语句不会再次检查,它会返回到yield return
之后的行,这是方法的结尾,因此完成。yield return
actually pauses execution and does a fake return (it yields a value) until the next one is requested. In this case, what happens is you check if the count is > 0 and then yield the next value. When the next one is requested, your if statement isn't checked again, it returns to the line after theyield return
which is the end of the method and thus it's done.“YIELD”的定义
在迭代器块中使用,向枚举器对象提供值或表示迭代结束。
我有错误阅读语法语句的良好记录,但我认为这意味着它必须位于迭代器块中,而您编写的不是。
也许将您的代码更改为;
The definition of "YIELD"
Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration.
I have an excellent record of reading syntax statements wrong but I think this means it has to be in an iterator block and the one you wrote is not.
Perhaps change your code to;