Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching ctrl+c event in console application (multi-threaded)

Tags:

c#

events

I have a main thread of a Console Application that runs few external processes this way

    private static MyExternalProcess p1;
    private static MyExternalProcess p2;
    private static MyExternalProcess p3;

    public void Main() {
        p1 = new MyExternalProcess();
        p2 = new MyExternalProcess();
        p3 = new MyExternalProcess();

        p1.startProcess();
        p2.startProcess();
        p3.startProcess();
    }

    public static void killEveryoneOnExit() {
        p1.kill();
        p2.kill();
        p3.kill();
    }


    class MyExternalProcess {
      private Process p;
      ...
      public void startProces() {
             // do some stuff
             PlayerProcess = new Process();
             ....
             PlayerProcess.Start();
             // do some stuff
      }

      public void kill() {
             // do some stuff
             p.Kill();
      }
    }          

What I need to do is: when the Main thread is interrupted (exit button or ctrl+c), the other processes should be killed. How do I trigger my method killEveryoneOnExit on CTRL+C or Exit (X) button?

like image 391
Manu Avatar asked Oct 20 '25 01:10

Manu


1 Answers

Based on your question there are two events you need to catch.

  • First there is the console close event which is explained here: "On Exit" for a Console Application
  • Second you want to catch control c which is explained here: How do I trap ctrl-c in a C# console app

If you put these two together with your example you get something like this:

static ConsoleEventDelegate handler;
private delegate bool ConsoleEventDelegate(int eventType);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

private static MyExternalProcess p1;

public static void Main()
{
    Console.CancelKeyPress += delegate
    {
        killEveryoneOnExit();
    };

    handler = new ConsoleEventDelegate(ConsoleEventCallback);
    SetConsoleCtrlHandler(handler, true);

    p1 = new MyExternalProcess();
    p1.startProcess();
}

public static void killEveryoneOnExit()
{
    p1.kill();
}

static bool ConsoleEventCallback(int eventType)
{
    if (eventType == 2)
    {
        killEveryoneOnExit();
    }
    return false;
}

For a working ctrl c (fun intended) paste example: http://pastebin.com/6VV4JKPY

like image 75
Jos Vinke Avatar answered Oct 21 '25 14:10

Jos Vinke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!