Application.Run 抛出 ArgumentException 未处理
我有一个需要关闭应用程序的情况,所以当我设置某个标志时,我调用 this.Dispose () 。
起初我以为是调用 this.Dispose() 后调用函数的问题,所以我将代码移动到最后调用的地方,但我仍然得到“ArgumentException was unhandled”“Parameter is not valid”。 在 Application.Run (new myApp (); 行上。
我做错了什么?我是否错过了一些东西?或者也许有更好的方法来关闭应用程序?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用
Application.Exit()
退出应用程序。当您使用
Application.Run(new MyForm());
时,会使用表单对象作为主表单在线程上创建消息循环。 它尝试将传入应用程序的 Win32 消息传递给各自的对象。 但是,当您在表单对象上调用Dispose()
时,您尚未退出消息循环。 当它尝试将下一条消息传递到表单对象时,它会失败,因为它已经被处理并抛出异常。 您应该请求关闭表单(通过在表单上调用Close
),然后请求表单处理事件,如果完成,则随后退出消息循环。 另一种方法(更直接的方法)是通过调用 Application.Exit() 来完全关闭线程上的消息循环,这将导致所有相关表单被关闭。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 callDispose()
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 callingClose
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 callingApplication.Exit()
which will cause all related forms to be closed.您应该使用 this.Close() 而不是 this.Dispose() 来关闭主窗体。
You should use this.Close() rather than this.Dispose() to close your main form.
如果您要关闭应用程序并因此卸载 AppDomain,则实际上不需要调用 Dispose(),因为 AppDomain 中的所有内容都将从内存中删除。
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.