问题
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);
}
}
回答1:
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();
}
}
回答2:
You can terminate the application with the Kill()
method of the current process.
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
Don't forget to use UseConsoleLifetime()
while building the host.
Host.CreateDefaultBuilder(args).UseConsoleLifetime(opts => opts.SuppressStatusMessages = true);
回答3:
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();
};
来源:https://stackoverflow.com/questions/50896621/net-core-how-to-properly-kill-started-process