在.NET中,是否有一种方法(如事件)用于检测控制台应用程序何时退出?我需要清理一些线程和COM对象。
我正在从控制台应用程序运行一个消息循环,没有表单。我正在使用的一个DCOM组件似乎要求应用程序泵送消息。
我已尝试将行程常式加入至Process.GetCurrentProcess.Exited和Process.GetCurrentProcess.Disposed。
我也尝试过给 * Application.ApplicationExit * 和 * Application.ThreadExit * 事件添加一个处理程序,但是它们没有触发。也许这是因为我没有使用窗体。
5条答案
按热度按时间jucafojl1#
您可以使用
AppDomain
的ProcessExit
事件:更新
下面是一个完整的示例程序,其中有一个空的“消息泵”运行在一个单独的线程上,它允许用户在控制台中输入一个退出命令,以优雅地关闭应用程序。在MessagePump中的循环之后,您可能希望以一种良好的方式清理线程使用的资源。在MessagePump中这样做比在ProcessExit中更好,原因如下:
代码如下:
nhaq1z212#
下面是一个完整的、非常简单的.NET解决方案,它可以在所有版本的Windows中工作。只需将它粘贴到一个新项目中,运行它,然后尝试Ctrl + C来查看它是如何处理的:
osh3o9ms3#
应用程序是一个服务器,它只运行到系统关闭或收到Ctrl + C或控制台窗口关闭为止。
由于应用程序的特殊性质,“优雅地”退出是不可行的。(我可能会编写另一个应用程序,它将发送“服务器关闭”消息,但这对于一个应用程序来说是多余的,而且对于某些情况(例如服务器(实际上是操作系统)实际上正在关闭)来说仍然是不够的。)
由于这些情况,我添加了一个“ConsoleCtrlHandler“,在那里我停止我的线程并清理我的COM对象,等等...
这个设置看起来很完美。下面是a link到一些C#代码的相同内容。
mrfwxfqh4#
对于CTRL+C的情况,您可以使用以下代码:
2izufjch5#
如果您使用的是控制台应用程序并且正在发送消息,则可以使用WM_QUIT消息。