集合被修改枚举操作可能无法执行线程安全c#

时间:2014-08-06 19:21:05

标签: c# multithreading

创建一个要从一个列表添加到列表框的线程时收到错误 这是代码

private void textBoxSearch_TextChanged(object sender, EventArgs e)
    {
        listBoxSuggest.Items.Clear();
       {
           string temp = ((TextBox)sender).Text;
           mythread = new Thread(()=> UpdateListBox(temp) );
           mythread.Start();
       }

    }

    private void UpdateListBox(string queyt)
    {
        if (queyt !=null)
        {
            if (myPrefixTree.Find(queyt))
            {
                var match = myPrefixTree.GetMatches(queyt);
                    foreach (string item in match)
                        this.Invoke((MethodInvoker)(() => listBoxSuggest.Items.Add(item)));
            }
        }

    }

我收到了错误

Collection was modified; enumeration operation may not execute.

我需要解决问题......

...更新 在运行程序时,我收到错误

  foreach (string item in match)

1 个答案:

答案 0 :(得分:3)

问题在于你调用了某些内容,例如.Add或.Remove,它在迭代过程中编辑枚举的内容。这会导致迭代失败,因为现在它不确定是否继续使用新元素(可能在当前索引之前设置索引)或跳过旧元素(可能已经处理过,或者甚至可能是当前项) )。

您需要确保任何可能修改其调用的循环内容的循环,而不是迭代该枚举的副本。 ToArrayToList都可以为此目的服务 -

foreach(var item in collection.ToArray()) ...

- 或 -

foreach(var item in collection.ToList()) ...

这意味着当某些东西不可避免地在循环体内某处调用collection.Add时,它会修改原始集合,而不是正在迭代的集合,从而防止出错。但是,它可能意味着它将处理迭代中较早删除的某些内容,在这种情况下,您可能需要更复杂的求解。