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)