System.InvalidOperationException:集合已修改 [英] System.InvalidOperationException: Collection was modified

查看:816
本文介绍了System.InvalidOperationException:集合已修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个下列异常,同时通过队列列举:

I am getting a following exception while enumerating through a queue:

System.InvalidOperationException:
集合已修改;枚举
操作可能不会执行

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的()。
的问题是,我该如何实现一个模式是否正确?

I think I understand the problem - altering the hashtable at action.Status = RecordStatus.Batched, which screws up the MoveNext() on enumerator. Question is, how do I implement that "pattern" correctly?

推荐答案

您被允许更改值集合中的一个项目。错误你得到一个项目要么添加或删除即:手段集合本身被修改,而不是集合中的一个项目。这是最有可能被另一个线程添加或删除项目到此集合引起的。

You are allowed to change the value in an item in a collection. The error you're getting means that an item was either added or removed i.e.: the collection itself was modified, not an item inside the collection. This is most likely caused by another thread adding or removing items to this collection.

您应该在你的方法开始锁定你的队列中,以防止其他线程修改集合当您访问它。或者你甚至可以调用此方法之前锁定集合

You should lock your queue at the beginning of your method, to prevent other Threads modifying the collection while you are accessing it. Or you could lock the collection before even calling this method.

private bool extractWriteActions(out List<WriteChannel> channelWrites)
    {
      lock(tpotActionQueue)
      {
        channelWrites = new List<WriteChannel>();
        foreach (TpotAction action in tpotActionQueue)
        {
            if (action is WriteChannel)
            {
                channelWrites.Add((WriteChannel)action);

                  action.Status = RecordStatus.Batched;

           }
        }
      }
       return (channelWrites.Count > 0);
   }

这篇关于System.InvalidOperationException:集合已修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆