问题
I have process A that starts process B.
they communicate in WCF (IAsyncResult APM Pattern), A is client B is service.
When Process A dies, i need to close B.
I am sending process A id as arg to process b and he does:
Process.GetProcessById(processId).WaitForExit();
This is working fine.
My question is how to kill process b properly if process a dies ?
I tried all the following:
Process.GetCurrentProcess().Close();
Process.GetCurrentProcess().Dispose();
Application.Exit(); > its a guiless winform application
The only thing that worked was:
Process.GetCurrentProcess().Kill();
But isnt killing the process is too brutal ?
Adding code:
Process B inside main:
TrackExternalProcess(externalProcessId, () => { OnExternalProcessClosed(); });
Public methods:
public static void TrackExternalProcess(int processId, Action onExternalProcessClosed)
{
new Thread(new ThreadStart(delegate
{
try
{
Thread.CurrentThread.IsBackground = true;
Process.GetProcessById(processId).WaitForExit();
logger.Error("Host process quit unexpectedly");
onExternalProcessClosed();
}
catch (Exception)
{
}
})).Start();
}
public static void OnExternalProcessClosed()
{
Process.GetCurrentProcess().Kill();
}
回答1:
Isn't Environment.Exit()
cleaner ?
回答2:
There was no cleaner version, I simply called my Dispose method.
It took care for everything, e.g closed WCF services.
And finally Process.GetCurrentProcess().Kill();
来源:https://stackoverflow.com/questions/15504686/best-way-to-close-hosted-process