Capture console exit C#

Total Post:104

Points:728
C# 
C#
 2904  View(s)
Ratings:
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.
  1. Post:412

    Points:2888
    Re: Capture console exit C#

    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);
      ...
    }

      Modified On Apr-03-2018 06:28:28 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!