gpt4 book ai didi

c# - 系统.InvalidOperationException : Collection was modified

转载 作者:太空狗 更新时间:2023-10-29 22:15:23 26 4
gpt4 key购买 nike

我在通过队列进行枚举时遇到以下异常:

System.InvalidOperationException: Collection was modified; enumeration operation may not execute

这里是代码摘录:

1:    private bool extractWriteActions(out List<WriteChannel> channelWrites)
2: {
3: channelWrites = new List<WriteChannel>();
4: foreach (TpotAction action in tpotActionQueue)
5: {
6: if (action is WriteChannel)
7: {
8: channelWrites.Add((WriteChannel)action);
9: lock(tpotActionQueue)
10: {
11: action.Status = RecordStatus.Batched;
12: }
13: }
14: }
15: return (channelWrites.Count > 0);
16: }

我想我理解这个问题 - 在 action.Status = RecordStatus.Batched 处更改哈希表,这会搞砸枚举器上的 MoveNext()。问题是,我该如何正确实现该“模式”?

最佳答案

我想我在 Collection 上使用 foreach 循环时遇到了类似的异常,我试图从 Collection 中删除项目(或者它可能是一个列表,我不记得了)。我最终通过使用 for 循环绕过了它。也许尝试以下操作:

for (int i=0; i<tpotActionQueue.Count(); i++)
{
TpotAction action = tpotActionQueue.Dequeue();
if (action is WriteChannel)
{
channelWrites.Add((WriteChannel)action);
lock(tpotActionQueue)
{
action.Status = RecordStatus.Batched;
}
}
}

关于c# - 系统.InvalidOperationException : Collection was modified ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1154350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com