best way to close hosted process

↘锁芯ラ 提交于 2019-12-10 09:42:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!