Home > DeveloperSection > Forums > Capture console exit C#
marcel ethan
marcel ethan

Total Post:105

Points:735
Posted on    December-12-2013 2:04 AM

 C# C# 
Ratings:


 1 Reply(s)
 1959  View(s)
Rate this:

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;


Please Help.


Pravesh Singh

Total Post:411

Points:2881
Posted on    December-12-2013 2:32 AM

Hi Marcel,

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:

  }

}

static void Main(string[] args)

{

  // Some biolerplate to react to close window event

  _handler += new EventHandler(Handler);

  SetConsoleCtrlHandler(_handler, true);

  ...

}


Don't want to miss updates? Please click the below button!

Follow MindStick