c# - 为什么 Application.Exit 无法工作?

标签 c# .net winforms

我有一个应用程序在从对话框中取消时出现奇怪的错误。如果框被取消,应用程序将无法继续,因此它退出,但由于某种原因它不工作,因此它继续运行并崩溃。

我调试了这个问题,应用程序以某种方式在 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/

相关文章:

c# - 以编程方式将文本粘贴到另一个应用程序的文本框中

c# - 来自 TryGetCachedRelatedEnd 的 Entity Framework 中的 NullReferenceException

c# - 在绘图面板中将鼠标光标更改为铅笔

C#-位图到字节数组

c# - 使用 Fluent.NHibernate,如何根据 Select 语句进行插入

c# - 使用 "Oracle.DataAccess"(带参数)在 C# 中调用 Oracle 存储过程

c# - 是否可以根据条件编译符号(预处理器常量)的值在 C# 项目中添加引用?

c# - 不能在同一类内的函数中使用变量声明类。为什么 ?

java - 哪些软件库可用于以编程方式创建照片马赛克?

.net - 使 WinForm 窗体在多个屏幕上最大化到桌面高度