C # System.InvalidOperationException: коллекция была изменена;операция перечисления может не выполняться - PullRequest
2 голосов
/ 14 июля 2011

Я исследовал эту проблему и еще не нашел того, что относится ко мне. Я не пытаюсь редактировать что-то, через что я зацикливаюсь.

************** Exception Text **************
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()

Вот моя функция, которая его вызывает:

internal static bool CloseAllForms()
{
    try
    {
        if (clsGlobal.g_objfrmCustomerInformation != null)
            clsGlobal.g_objfrmCustomerInformation.Close();
        if (clsGlobal.g_objfrmSearchCustomer != null)
            clsGlobal.g_objfrmSearchCustomer.Close();

        if (clsGlobal.g_objfrmSwipeLicense != null)
            clsGlobal.g_objfrmSwipeLicense.Close();

        if (clsGlobal.g_objfrmSearchResults != null)
            clsGlobal.g_objfrmSearchResults.Close();

        if (clsGlobal.g_objfrmCustomerData != null)
            clsGlobal.g_objfrmCustomerData.Close();
        if (clsGlobal.g_objfrmPurchaseOrder != null)
            clsGlobal.g_objfrmPurchaseOrder.Close();
        if (clsGlobal.g_objfrmAddPurchaseOrderItem != null)
            clsGlobal.g_objfrmAddPurchaseOrderItem.Close();
        if ((clsGlobal.g_objfrmCustomerInformation == null) && (clsGlobal.g_objfrmSearchCustomer == null) && (clsGlobal.g_objfrmSwipeLicense == null) && (clsGlobal.g_objfrmSearchResults == null) && (clsGlobal.g_objfrmCustomerData == null) && (clsGlobal.g_objfrmPurchaseOrder == null) && (clsGlobal.g_objfrmAddPurchaseOrderItem == null))
        {
            PrepareImageBar();
            return true;
        }
        else
        {
            PrepareImageBar();
            return false;
        }
    }
    catch (Exception ex)
    {
        string ErrorMessage;

        ErrorMessage = "Error: " + ex.Message +
           "\r\nSource: " + ex.Source +
           "\r\nTargetSite: " + ex.TargetSite.ToString() +
           "\r\nStackTrace: " + ex.StackTrace.ToString();

        if (ex.Data.Count > 0)
        {
            ErrorMessage += "\r\nData Count: " + ex.Data.Count.ToString() +
                "\r\nKeys: " + ex.Data.Keys.ToString() +
                "\r\nValues: " + ex.Data.Values.ToString();
        }

        MessageBox.Show(ErrorMessage, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
        CustomFunctions.emailExceptionToAuthor(ex);

        return false;
    }
}

Вот как я вызываю функцию:

if (CloseAllForms())
{
    if (clsGlobal.g_objfrmPurchaseOrder == null)
    {
        clsGlobal.g_objfrmPurchaseOrder = new frmPurchaseOrder();

        clsGlobal.g_objfrmPurchaseOrder.FormClosed += PurchaseOrderFormClosed;
        clsGlobal.g_objfrmPurchaseOrder.MdiParent = clsGlobal.g_objfrmMDIMain;
        clsGlobal.g_objfrmPurchaseOrder.Show();
        clsGlobal.g_objfrmPurchaseOrder.BringToFront();
    }
    else
    {
        clsGlobal.g_objfrmPurchaseOrder.Show();
        clsGlobal.g_objfrmPurchaseOrder.BringToFront();
    }

    PrepareImageBar();
}

Пожалуйста, помогите мне!

ОБНОВЛЕНИЕ: Вот полный код.

Исключение Смотрите в конце этого сообщения подробности о вызове Отладка по времени (JIT) вместо этого диалогового окна.

************** Exception Text **************
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at Microsoft.VisualBasic.PowerPacks.ShapeCollection.Dispose(Boolean disposing)
at Microsoft.VisualBasic.PowerPacks.ShapeContainer.Dispose(Boolean disposing)
at System.ComponentModel.Component.Dispose()
at System.Windows.Forms.Control.Dispose(Boolean disposing)
at System.Windows.Forms.Form.Dispose(Boolean disposing)
at B2HD_Software.frmCustomerData.Dispose(Boolean disposing)
at System.Windows.Forms.Form.WmClose(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

PrepareImageBar ();

internal static void PrepareImageBar()
{
clsGlobal.g_objfrmMDIMain.mnuImageBarAddCustomer.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarAddCustomer.Enabled = true;
clsGlobal.g_objfrmMDIMain.mnuImageBarEditCustomer.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarEditCustomer.Enabled = true;
clsGlobal.g_objfrmMDIMain.mnuImageBarFindCustomer.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarFindCustomer.Enabled = true;
clsGlobal.g_objfrmMDIMain.mnuImageBarStartSearch.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarStartSearch.Enabled = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarSwipeLicense.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarSwipeLicense.Enabled = true;
clsGlobal.g_objfrmMDIMain.mnuImageBarViewNotes.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarViewNotes.Enabled = true;
clsGlobal.g_objfrmMDIMain.mnuImageBarNewPurchase.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarNewPurchase.Enabled = true;
clsGlobal.g_objfrmMDIMain.mnuImageBarAddItem.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarAddItem.Enabled = true;
clsGlobal.g_objfrmMDIMain.mnuImageBarModifyItem.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarModifyItem.Enabled = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarDeleteItem.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarDeleteItem.Enabled = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarTakePicture.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarTakePicture.Enabled = true;
clsGlobal.g_objfrmMDIMain.mnuImageBarSavePicture.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarSavePicture.Enabled = true;
clsGlobal.g_objfrmMDIMain.mnuImageBarSave.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarSave.Enabled = true;
clsGlobal.g_objfrmMDIMain.mnuImageBarCancel.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarCancel.Enabled = true;
clsGlobal.g_objfrmMDIMain.mnuImageBarAdmin.Visible = false;
clsGlobal.g_objfrmMDIMain.mnuImageBarAdmin.Enabled = true;

switch (clsGlobal.ActiveForm())
{
    case "CustomerInformation":
        clsGlobal.g_objfrmMDIMain.mnuImageBarTakePicture.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarSave.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarCancel.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarCancel.Enabled = true;

        break;
    case "SearchCustomer":
        clsGlobal.g_objfrmMDIMain.mnuImageBarStartSearch.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarSwipeLicense.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarCancel.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarStartSearch.Enabled = false;

        break;
    case "SwipeLicense":
        clsGlobal.g_objfrmMDIMain.mnuImageBarCancel.Visible = true;

        break;
    case "CustomerData":
        clsGlobal.g_objfrmMDIMain.mnuImageBarCancel.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarViewNotes.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarNewPurchase.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarEditCustomer.Visible = true;

        break;
    case "PurchaseOrder":
        clsGlobal.g_objfrmMDIMain.mnuImageBarCancel.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarAddItem.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarDeleteItem.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarModifyItem.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarEditCustomer.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarViewNotes.Visible = true;

        clsGlobal.g_objfrmPurchaseOrder.ShowProperButtons();

        break;
    case "AddPurchaseOrderItem":
        clsGlobal.g_objfrmMDIMain.mnuImageBarTakePicture.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarSave.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarCancel.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarViewNotes.Visible = true;

        break;

    default:
        clsGlobal.g_objfrmMDIMain.mnuImageBarAddCustomer.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarFindCustomer.Visible = true;
        clsGlobal.g_objfrmMDIMain.mnuImageBarSwipeLicense.Visible = true;

        break;
}
}

CloseAllForms ()

internal static bool CloseAllForms()
{
if (clsGlobal.g_objfrmCustomerInformation != null)
    clsGlobal.g_objfrmCustomerInformation.Close();

if (clsGlobal.g_objfrmSearchCustomer != null)
    clsGlobal.g_objfrmSearchCustomer.Close();

if (clsGlobal.g_objfrmSwipeLicense != null)
    clsGlobal.g_objfrmSwipeLicense.Close();

if (clsGlobal.g_objfrmSearchResults != null)
    clsGlobal.g_objfrmSearchResults.Close();

if (clsGlobal.g_objfrmCustomerData != null)
    clsGlobal.g_objfrmCustomerData.Close();

if (clsGlobal.g_objfrmPurchaseOrder != null)
    clsGlobal.g_objfrmPurchaseOrder.Close();

if (clsGlobal.g_objfrmAddPurchaseOrderItem != null)
    clsGlobal.g_objfrmAddPurchaseOrderItem.Close();

if ((clsGlobal.g_objfrmCustomerInformation == null) && (clsGlobal.g_objfrmSearchCustomer == null) && (clsGlobal.g_objfrmSwipeLicense == null) && (clsGlobal.g_objfrmSearchResults == null) && (clsGlobal.g_objfrmCustomerData == null) && (clsGlobal.g_objfrmPurchaseOrder == null) && (clsGlobal.g_objfrmAddPurchaseOrderItem == null))
{
    PrepareImageBar();
    return true;
}
else
{
    PrepareImageBar();
    return false;
}

}

Вот так выглядит мое закрытое событие в каждой форме.

internal static void CustomerInformationFormClosed(object sender, FormClosedEventArgs e)
    {
        clsGlobal.g_objfrmCustomerInformation = null;

        PrepareImageBar();
    }

Ответы [ 3 ]

1 голос
/ 15 июля 2011

Я вижу три возможности:

  1. Что-то не так в обработчике событий FormClosed для одной из форм (т. Е. Может быть что-то в PurchaseOrderFormClosed).
  2. Ваш метод CloseAllForms() выполняет кучу работы в catch. Вполне возможно, что код там терпит неудачу. Когда происходит ошибка, вы видите MessageBox? Письмо отправлено? Попробуйте закомментировать весь код и посмотрите, все ли еще возникла ошибка. Или, может быть, просто временно замените весь код в catch на MessageBox.Show(ex.ToString()), чтобы вы могли быть уверены, что наблюдаемое исключение происходит в try.
  3. Что-то не получается в PrepareImageBar(). Попробуйте закомментировать этот метод и посмотрите, по-прежнему ли вы получаете ошибку.
1 голос
/ 14 июля 2011

Я не знаю, где произошло исключение, но исключение может быть сгенерировано в foreach кодовом блоке, где коллекция была изменена.Здесь модификация означает «Добавить» или «Удалить» что-то вроде:

foreach(var item in collection)    { collection.Add(other);}

Коллекция не может быть изменена при перечислении.


ОБНОВЛЕНО

Чтобы найти, где это произошло, если вы находились в вашем коде во время отладки, вы должны проверить «опцию необработанного пользователя» в диалоге исключений (Ctrl + Alt + E).Однако, обратите внимание, что для использования этой опции VS должен быть установлен «Включить только мой код» в опции отладки.

0 голосов
/ 12 апреля 2012

Я видел эту ошибку: ошибка, по-видимому, появляется только при некоторых установках Windows, и я никогда не сталкивался с ней в среде разработки через отладку, только в полном приложении.

Этоошибка в VisualBasic.PowerPacks.

См. здесь решение (см. конец блога).

В основном вам необходимо переопределить формы Dispose ()метод и вручную утилизировать все элементы VisualBasic Powerpack.

...