Today I wanted to Show a Modal Dialog until something was stored in the FormClosing event. For some reason at another point in an UnhandledExeptionHandler I called Application.Exit(). The result was another Exception "Collection was modified; enumeration operation may not execute"...
I was abled to reproduce this effect in a very simple WinForms-example with two forms and a button:
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
using (var frm = new Form2())
{
frm.ShowDialog();
}
}So the clue is that Application.Exit enumerates its forms and raises the FormClosing event - which... opens a window on its own and so modifies the Applications Form Enumeration which led to this bug.
btw a MessageBox.Show did NOT produce this problem maybe because its just mapped to an Win32 API-Call that wont modify the .NET-Applications-Formlist.
I worked around that problem by simply Closing the Window instead (or just before App.Exit).