首页 > 解决方案 > 当父进程关闭时,使用 WaitForExit() 杀死子进程

问题描述

program.exe我有 ac# .netcore 应用程序,它通过 StandardOutput 和 StandardInput与外部基于命令行的程序(我们称之为)进行交互。program.exe将永远运行,除非它被明确告知关闭(通过发送exit到 StandardInput)。

问题是我需要这个程序在我关闭时关闭(无论如何),但我还需要Process.WaitForExit()在它启动后调用,以便刷新输出缓冲区,并实际接收程序的输出。因此,我也在一个单独的线程中运行这整个操作,这样WaitForExit()就不会阻塞我的应用程序的其余部分。

这是正在发生的事情的一个稍微简化的示例:

public static class BackgroundProcess
{
    //Called by my application to start the associated process in a new thread
    public static void Start()
    {
        Thread worker = new Thread(RunBackgroundProcess);
        worker.IsBackground = true;
        worker.Start();
    }
    static Process backgroundProcess;
    public static void RunBackgroundProcess()
    {
        backgroundProcess = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "program.exe",
                Arguments = "start",
                UseShellExecute = false,
                RedirectStandardOutput = true
            }
        }
        backgroundProcess.OutputDataReceived += BackgroundProcess_OutputDataReceived;
        backgroundProcess.Start();
        backgroundProcess.BeginOutputReadLine();
        backgroundProcess.WaitForExit(); //required in order to flush the output buffer
    }
    private static void BackgroundProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        DoStuffWithData(e.Data);
    }
}

据我所知,它是在单独的线程中启动进程和在我的应用程序关闭后.WaitForExit()保持program.exe打开状态的组合:如何在不使用的情况下刷新输出缓冲区.WaitForExit(),或者确保在我的应用程序运行时它仍然被杀死?

另请注意,除了 Windows 之外,此应用程序还需要与 macOS 和 Linux 保持兼容。

标签: c#multithreading.net-core

解决方案


推荐阅读