繁体   English   中英

集合被修改枚举操作可能无法执行

[英]collection was modified enumeration operation may not execute

好的,所以我想打开一个新表格,如果还没有打开。 所以我根据表格的标题或文字检查表格。 现在,到目前为止它的工作原理,如表格打开,如果它已经打开,它只是将它带到前面。 但我的问题是,如果它没有打开,我尝试创建它的新实例,它会抛出“收集被修改;枚举操作可能无法执行”。 而我无法为我的生活找出原因。 任何帮助表示赞赏。

foreach (DataRow iRow in chatcheck.Rows)
{
   FormCollection fc = Application.OpenForms;
   foreach (Form f in fc)
   {
      if (f.Text != ChatReader["Sender"].ToString())
      {

         ChatBox chat = new ChatBox();
         Connection.ConnectionStrings.chatopen = ChatReader["Sender"].ToString();
         chat.Text = Connection.ConnectionStrings.chatopen;
         chat.Show();
         chat.BringToFront();

      }
      else if (f.Text == ChatReader["Sender"].ToString())
      {
              f.BringToFront();
      }
   }
}

不要使用foreach而是使用for -loop:

for (int i = 0; i < Application.OpenForms.Count; i++ )
{
    Form f = Application.OpenForms[i];
    if (f.Text != ChatReader["Sender"].ToString())
    {

        //...
        chat.Show();
        chat.BringToFront();
    }
    // ...
}

您可以在枚举期间更改foreach的基础集合。 但如果您创建一个新表单并在那里显示它,就会发生这种情况。 您将另一个表单添加到open-collection。

您可以将信息保存在foreach循环中(例如,在List <>中),然后使用此信息打开表单。

                var myList = new List<something>();
                foreach (DataRow iRow in chatcheck.Rows)
                {
                    FormCollection fc = Application.OpenForms;
                    foreach (Form f in fc)
                    {
                        if (f.Text != ChatReader["Sender"].ToString())
                        {
                           myList.Add(...)
                        }
                        else if (f.Text == ChatReader["Sender"].ToString())
                        {
                            f.BringToFront();
                        }
                    }
                }

foreach (var val in myList)
{
   ChatBox chat = new ChatBox();
   ...
}

为什么不在循环和修改Dictionary时使用foraeach 我们可以使用foreach循环遍历字典,其密钥如下:

            //get key collection from dictionary into a list to loop through    
            List<int> keys = new List<int>(Dictionary.Keys);

            // iterating key collection using simple for-each loop
            foreach (int key in keys)
            { 
                // Now we can perform any modification with values of dictionary.    
                Dictionary[key] = Dictionary[key] - 1; 

            }

这是一篇关于它的帖子: 如何在C#中使用键迭代字典

真实代码在WinForms应用程序的MainForm中。

    /// <summary>
    /// Creates and connects the hub connection and hub proxy. 
    /// </summary>
    private async void ConnectWithRetryAsync()
    {
        Connection = new HubConnection(Properties.Settings.Default.ServerBaseUrl);
        Connection.Closed += Connection_Closed;
        Connection.Error += Connection_Error;
        HubProxy = Connection.CreateHubProxy("signalcalendar");

        //Handle incoming event from server: use Invoke to write to log from SignalR's thread
        HubProxy.On<CalendarUpdateRequest>("UpdateCalendarEvent", (calendarUpdateRequest) =>
            this.Invoke((Action)(() =>
            {
                try
                {
                    if (calendarUpdateRequest == null) return;

                    // Reject my own calendar's changes
                    if (calendarUpdateRequest.UserInfo.UserId == Program.UserInfo.UserId) return;

                    //Notify all opened Form about Calendar changes
                    for (int i = 0; i < Application.OpenForms.Count; i++)
                    {
                        var openForm = Application.OpenForms[i];

                        try
                        {
                            var currentFormType = openForm.GetType();
                            if (currentFormType == typeof(CommonForm))
                            {
                                if ((openForm as CommonForm).AppWindowType == AppWindowTypes.FactTruckForm ||
                                    (openForm as CommonForm).AppWindowType == AppWindowTypes.PlanTruckForm ||
                                    (openForm as CommonForm).AppWindowType == AppWindowTypes.FactExcForm ||
                                    (openForm as CommonForm).AppWindowType == AppWindowTypes.PlanExcForm)
                                {
                                    (openForm as CommonForm).CalendarHasBeenChanged(calendarUpdateRequest);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                }
            }
            ))
        );

        #region  Connect to the Server
        try
        {
            await Connection.Start();
        }
        catch (HttpRequestException ex)
        {
            var errorMessage = "There is no connection with Server. Check your netwrok and Server App state";
            logger.Error(errorMessage);
            logger.Error(ex);

            MetroMessageBox.Show(this, errorMessage, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

            Close();
        }

        #endregion

        //Activate UI          
        logger.Info("COnnection has been established OK");
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM