ZeroKelvin ZeroKelvin - 1 year ago 174
C# Question

Capture console exit 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.

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;

flq flq
Answer Source

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...

private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

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

enum CtrlType

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:
          return false;

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download