Application.Run throws ArgumentException was unhandled

倾然丶 夕夏残阳落幕 提交于 2019-12-08 04:16:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!