我有一个应用程序在从对话框中取消时出现奇怪的错误。如果框被取消,应用程序将无法继续,因此它退出,但由于某种原因它不工作,因此它继续运行并崩溃。
我调试了这个问题,应用程序以某种方式在 Application.Exit 调用之后运行。我在 Debug模式下运行,这是相关的,因为有少量代码取决于所定义的 RELEASE 变量。这是我的应用程序退出代码。我已经跟踪代码,它进入了 ExitApp 方法,并继续执行,将控制权返回给调用者并最终崩溃。
这是一个通过远程桌面连接提供报告的应用程序,因此退出代码有点奇怪。它试图终止远程 session ,但仅在发布时运行,因为我不想在每次测试运行时关闭我的开发机器。
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
我在 Application.Exit 行之后运行了一个调试器,但没有任何反应,然后在我越过该行后控制权返回给调用者。
这是怎么回事?这是一个 Windows 窗体应用程序。
最佳答案
这篇文章扩展了您正在经历的相同思路:http://www.dev102.com/2008/06/24/how-do-you-exit-your-net-application/
基本上:
Environment.Exit - From MSDN: Terminates this process and gives the underlying operating system the specified exit code. This is the code to call when you are using console application.
Application.Exit - From MSDN: Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application. There are some more issues about this method, read about it in the MSDN page.
对此的另一个讨论:Link
这篇文章指出了一个很好的提示:
您可以通过检查 System.Windows.Forms.Application.MessageLoop 属性来确定是否已调用 System.Windows.Forms.Application.Run。如果为真,则 Run 已被调用,您可以假设 WinForms 应用程序正在执行如下。
if (System.Windows.Forms.Application.MessageLoop)
{
// Use this since we are a WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Use this since we are a console app
System.Environment.Exit(1);
}
关于c# - 为什么 Application.Exit 无法工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/554408/