Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#关闭进程并在进程上运行代码_C#_Process_Exit - Fatal编程技术网

C#关闭进程并在进程上运行代码

C#关闭进程并在进程上运行代码,c#,process,exit,C#,Process,Exit,我想在应用程序退出时运行代码。我的问题是我有两个申请。第一个是跑步。我的第二个应用程序现在将关闭第一个应用程序。但在结束时,我想在第一个应用程序中运行代码 public class First { public static Main(string[] args) { Console.ReadLine(); } public void DoSomethingOnExit() { Console.WriteLine("It Works");

我想在应用程序退出时运行代码。我的问题是我有两个申请。第一个是跑步。我的第二个应用程序现在将关闭第一个应用程序。但在结束时,我想在第一个应用程序中运行代码

public class First
{
   public static Main(string[] args)
   {
        Console.ReadLine();
   }

  public void DoSomethingOnExit()
  {
    Console.WriteLine("It Works");
    Thread.Sleep(1000);
  }
}


public class Second
{
    public void method(int number)
    {
        var prozess = Process.GetProcessById(number);
        prozess.Close();
    }   
}
试试这个

static void Main(string[] args)
    {
        _handler += new EventHandler(Handler);
        SetConsoleCtrlHandler(_handler, true);

        Console.WriteLine("Running");            
        Console.ReadLine();            
    }



 [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:
                DoSomeShutdownStuff();
                return true;

            default:
                return false;
        }
    }

您可以使用命名管道或其他类型的进程间通信。它是控制台应用程序吗?如果是这样的话,那么应该将其分为两个问题,一个是关于在应用程序退出时执行方法的问题,另一个是关于两个应用程序之间的通信的问题。一个是缺乏研究,另一个是关于使用SO作为代码服务。