Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net core - How to properly kill started process?

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);
    }
}
like image 669
Liran Friedman Avatar asked Jun 17 '18 12:06

Liran Friedman


People also ask

How to kill process in asp Net?

To force the application to quit, use the Kill method. The behavior of CloseMainWindow is identical to that of a user closing an application's main window using the system menu. Therefore, the request to exit the process by closing the main window does not force the application to quit immediately.


1 Answers

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();
    }
}
like image 90
Liran Friedman Avatar answered Oct 19 '22 20:10

Liran Friedman