在控制台应用程序中捕获ctrl + c事件(多线程)

时间:2013-11-03 22:05:34

标签: c# events

我有一个控制台应用程序的主线程,它以这种方式运行很少的外部进程

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

我需要做的是:当主线程被中断时(退出按钮或ctrl + c),其他进程应被终止。 如何在CTRL + C或Exit(X)按钮上触发我的方法killEveryoneOnExit?

1 个答案:

答案 0 :(得分:5)

根据您的问题,您需要捕捉两个事件。

如果你把这两个放在你的例子中,你会得到这样的东西:

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

对于工作ctrl c(有趣的)粘贴示例:http://pastebin.com/6VV4JKPY