.net core - 如何正确杀死已启动的进程?

时间:2018-06-17 12:25:33

标签: c# asp.net-core-2.0

我有一个dotnet core 2.0控制台应用程序启动了另一个dotnet核心WebAPI。 问题是,当控制台应用程序关闭时,如何干净地杀死WebAPI进程?因为到目前为止,我无法启动该过程两次,因为它给出了地址正在使用的错误,我仍然可以在任务管理器中看到该过程。

以下是我尝试这样做的方法,但似乎错过了完全杀死所有进程的内容:

class Program
{
    static Process cmd;

    static async Task Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

        var startInfo = new ProcessStartInfo("cmd.exe")
        {
            UseShellExecute = false,
            RedirectStandardInput = true,
            CreateNoWindow = true,
        };

        cmd = new Process { StartInfo = startInfo };

        cmd.Start();

        using (cmd)
        {
            cmd.StandardInput.WriteLine($"cd C:/Project/publish");
            cmd.StandardInput.WriteLine($"dotnet WebAPI.dll");
            cmd.WaitForExit();
        }
    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Process.GetProcessById(cmd.Id).Kill();
        Environment.Exit(0);
    }
}

3 个答案:

答案 0 :(得分:0)

正如@mjwills所建议,我已按如下方式更新了该流程:

class Program
{
    static Process webAPI;

    static async Task Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

        webAPI = new Process
        {
            StartInfo = new ProcessStartInfo("dotnet")
            {
                UseShellExecute = false,
                WorkingDirectory = "C:/Project/publish",
                Arguments = "WebAPI.dll",
                CreateNoWindow = true
            }
        };
        using (webAPI)
        {
            webAPI.Start();
            webAPI.WaitForExit();
        }
    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        webAPI.Close();
    }
}

答案 1 :(得分:0)

您可以使用当前进程的Kill()方法终止应用程序。

Startup.cs

        public void Configure(IHostApplicationLifetime appLifetime)
        {
            //...

            appLifetime.ApplicationStarted.Register(() =>
            {
                Console.WriteLine("Press Ctrl+C to shut down.");
            });

            appLifetime.ApplicationStopped.Register(() =>
            {
                Console.WriteLine("Shutting down...");
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            });
        }

Program.cs

在构建主机时不要忘记使用UseConsoleLifetime()

Host.CreateDefaultBuilder(args).UseConsoleLifetime(opts => opts.SuppressStatusMessages = true);

答案 2 :(得分:-1)

 class first_class{

static Process[] cmd=new Process[size];
      int main(){
           cmd[0] = new Process { StartInfo = startInfo };

           cmd[0].Start();
      }
};

===============================================

ref class otherClass{

first_class::cmd[0].Kill();

};