本文介绍了捕获控制台退出 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含相当多线程的控制台应用程序.有些线程会监视某些条件并在它们为真时终止程序.这种终止可能随时发生.

I have a console application that contains quite a lot of threads. There are threads that monitor certain conditions and terminate the program if they are true. This termination can happen at any time.

我需要一个可以在程序关闭时触发的事件,以便我可以清理所有其他线程并正确关闭所有文件句柄和连接.我不确定 .NET 框架中是否已经内置了一个,所以我在编写自己的框架之前先询问一下.

I need an event that can be triggered when the program is closing so that I can cleanup all of the other threads and close all file handles and connections properly. I'm not sure if there is one already built into the .NET framework, so I'm asking before I write my own.

我想知道是否有类似以下内容的事件:

I was wondering if there was an event along the lines of:

MyConsoleProgram.OnExit += CleanupBeforeExit;

推荐答案

我不确定在网络上的何处找到该代码,但我现在在我的一个旧项目中找到了它.这将允许您在控制台中执行清理代码,例如当它突然关闭或由于关机...

I am not sure where I found the code on the web, but I found it now in one of my old projects. This will allow you to do cleanup code in your console, e.g. when it is abruptly closed or due to a shutdown...

[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

private delegate bool EventHandler(CtrlType sig);
static EventHandler _handler;

enum CtrlType
{
  CTRL_C_EVENT = 0,
  CTRL_BREAK_EVENT = 1,
  CTRL_CLOSE_EVENT = 2,
  CTRL_LOGOFF_EVENT = 5,
  CTRL_SHUTDOWN_EVENT = 6
}

private static bool Handler(CtrlType sig)
{
  switch (sig)
  {
      case CtrlType.CTRL_C_EVENT:
      case CtrlType.CTRL_LOGOFF_EVENT:
      case CtrlType.CTRL_SHUTDOWN_EVENT:
      case CtrlType.CTRL_CLOSE_EVENT:
      default:
          return false;
  }
}


static void Main(string[] args)
{
  // Some biolerplate to react to close window event
  _handler += new EventHandler(Handler);
  SetConsoleCtrlHandler(_handler, true);
  ...
}

更新

对于那些不检查评论的人来说,这个特定的解决方案似乎在 Windows 7效果不佳(或根本无法).以下 thread 谈到这个

For those not checking the comments it seems that this particular solution does not work well (or at all) on Windows 7. The following thread talks about this

这篇关于捕获控制台退出 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 05:15