本文介绍了"集合已修改;枚举操作可能不会执行“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

集合已被修改;枚举操作可能无法执行"为什么在执行我的以下代码时会出现此错误:

这是我在.Net中的窗口表单应用程序

1.我正在使用Global类读取实例消息并将其显示给Textbox
2.它执行得很好,但有时会在第二个foreach循环中显示类似集合已被修改;枚举操作可能无法执行"之类的错误,例如

"Collection was modified; enumeration operation may not execute " Why this error is coming when execute my below code:

This is my Window Form Application in .Net

1.I am using a Global class for reading instance message and shown it to a Textbox
2.It is executing fine but some time showing error like "Collection was modified; enumeration operation may not execute " in second foreach looping like

foreach (var values in dict[item])
                   {



3.我的全局类是在其中将值存储在Dictionary对象中并从中检索的.



3. My global Class is in which i am storing value in Dictionary object and retrived from that .

public static class GlobalVariables
    {

       public static Dictionary<string,>> dictionary = new Dictionary<string,>>();

        public static void SetMessage(String DBName, String Message)
        {


            if (dictionary.ContainsKey(DBName))
            {
                //dictionary.Remove(DBName);
                List<string> list = new List<string>();
                list.Clear();
                list.Add(Message);
                dictionary[DBName]=list;

            }
            else
            {

                    List<string> list = new List<string>();
                    list.Add(DateTime.Now.ToString());
                    dictionary.Add("Process Started",list);


            }


        }

    }


4.在这里,我们可以在字典对象的文本框中显示消息,并在第二个foreach行中显示错误,例如


4.Here we can show the message in textbox from Dictionary object and error shown in the second foreach line like

foreach (var values in dict[item])
                    {







public void setTextBoxValue()
      {
          //Thread.Sleep(1000);
          Dictionary<string, List<string>> dict = GlobalVariables.dictionary;
            //string strMessage = Convert.ToString(GlobalVariables.message);

            if (dict.Keys.Count > 0)
            {
                builder.Remove(0, builder.Length);

                foreach (var item in dict.Keys)
                {

                    foreach (var values in dict[item])
                    {

                       string message = item + ":" + values.ToString();

                       builder.AppendLine(message);

                       builder.Append("\n\n");

                      textBox1.Text = builder.ToString();


                    }


                }
                Application.DoEvents();

            }


        }

推荐答案


这篇关于&quot;集合已修改;枚举操作可能不会执行“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 17:10
查看更多