问题
I have a condition in which I need to close the application and so I call this.Dispose () when I set a certian flag.
At first I thought it was a problem of calling functions after I call this.Dispose () and so I moved the code to be the last thing called, but I still get an "ArgumentException was unhandled" "Parameter is not valid." On the Application.Run (new myApp (); line.
What am I doing wrong? Did I miss something along the way? Or maybe there is a better way to close the application?
回答1:
Try using Application.Exit()
to exit the application.
When you use Application.Run(new MyForm());
, a message loop is created on the thread using the form object as the main form. It tries to deliver Win32 messages that are coming to the application to their respective objects. However, when you call Dispose()
on the form object, you haven't exited the message loop yet. When it tries to deliver the next message to your form object, it fails since it's already disposed and throws the exception. You should either request the form to be closed (by calling Close
on the form), which will then ask the form to process the event and if completed, exit the message loop afterwards. The other way (more direct way) is to shut down the message loop on the thread altogether by calling Application.Exit()
which will cause all related forms to be closed.
回答2:
You should use this.Close() rather than this.Dispose() to close your main form.
回答3:
if you're closing the app and thus unloading the AppDomain you don't really need to call Dispose() since everything from the AppDomain will be removed from memory.
来源:https://stackoverflow.com/questions/389551/application-run-throws-argumentexception-was-unhandled