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);
}
}
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With