.net core-如何正确杀死启动的进程? [英] .net core - How to properly kill started process?

查看:1293
本文介绍了.net core-如何正确杀死启动的进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dotnet core 2.0 console app that starts up another dotnet core WebAPI. The problem is, how do I cleanly kill the WebAPI process when the console app is closed? Because as of now, I can't start the process twice since it gives an error the address is in use, and I can still see the process in the task manager.

这是我尝试执行的操作,但似乎丢失了一些东西来完全杀死所有进程:

Here is how I tried to do that but seems like it's missing something to completely kill all the processes:

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

推荐答案

按照@mjwills的建议,我已对流程进行了如下更新:

As suggested by @mjwills I've updated the process as follows:

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

这篇关于.net core-如何正确杀死启动的进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆