Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

c# - System.InvalidOperationException due to collection modification on call to Application.Exit()

I've got this really, really weird error that I've never been able to pin down (it happens very rarely). Basically, I have a C# application that was randomly throwing an unknown exception on exit. I've managed to catch it in the debugger this time, and it turns out that calling Application.Exit() is throwing a System.InvalidOperationException with the following message:

A first chance exception of type 'System.InvalidOperationException' occurred in mscorlib.dll

Additional information: Collection was modified; enumeration operation may not execute.

I'm not sure what this collection that has been allegedly modified is, or who it was that modified it.

The stack trace isn't very helpful:

mscorlib.dll!System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext() + 0x13f bytes System.Windows.Forms.dll!System.Windows.Forms.Application.ExitInternal() + 0x112 bytes System.Windows.Forms.dll!System.Windows.Forms.Application.Exit(System.ComponentModel.CancelEventArgs e) + 0x65 bytes

Any idea how I can find out which ArrayList it is that has been modified? I don't think it's anything I'm doing explicitly, more likely an action I'm doing that's modifying the underlying state of the .NET framework during the middle of an operation that MS wasn't expecting..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unusual, never seen this before. The Application.ExitInternal() method iterates the Application.OpenForms collection. Clearly this collection is getting modified while it is doing so. There are few possible causes for this, I can only come up with one. One of your forms has overridden the OnFormClosing() method or subscribed the FormClosing event. And is doing something that modifies the OpenForms collection. Could be disposing the form object or creating a new form instance or modifying a form property that causes the window to be re-created, like ShowInTaskbar.

You won't find this code back in the call stack. Review your On/FormClosing code. Comment code out if you can't find it quickly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...