简体   繁体   中英

InvalidOperationException on Application.Exit

Can someone tell me why the exitToolStripMenuItem_Click throws an InvalidOperationException. I know it happens due to plugin.Close() being called. However, I do not understand why. Closing the Form1 via the "X" button does not trigger the exception. Calling Application.Exit() does though. Below is a sample to demonstrate what is happening in my main app. In my main app events are triggered off certain forms closing so I need to make sure I call Close on each forms. I could change Application.Exit() to a Close() however after reading MSDN I don't feel like this is the correct solution. Any ideas would be helpful, thanks.

Note: The main application I'm working on is multi-threaded.

public partial class Form1 : Form
{
    Form plugin = new Form();
    public Form1()
    {
        InitializeComponent();
        plugin.Show();
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        plugin.Close();
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }
}

The exception thrown is:

Exception thrown: 'System.InvalidOperationException' in mscorlib.dll
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
   at System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext()
   at System.Windows.Forms.Application.ExitInternal()
   at System.Windows.Forms.Application.Exit(CancelEventArgs e)
   at System.Windows.Forms.Application.Exit()
   at WindowsFormsApplication2.Form1.exitToolStripMenuItem_Click(Object sender, EventArgs e)

You don't need Application.Exit() in exitToolStripMenuItem_Click() . Calling Application.Exit , will close and dispose the form, while resuming the execution at exitToolStripMenuItem_Click , ObjectDisposedException would be thrown. Also, System.InvalidOperationException would be thrown as Windows Forms collection has been modified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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