views:

751

answers:

3

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 a "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? Thanks for the help in advance.

A: 

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.

Mladen Prajdic
+4  A: 

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.

Mehrdad Afshari
Why that worked perfectly, I would kiss you, but then I bet I would get banned by stackoverflow :)
Matt
I updated the answer to clarify
Mehrdad Afshari
+1  A: 

You should use this.Close() rather than this.Dispose() to close your main form.

Joe