在C#中如何在一定时间后强制关闭进程?

3
我得到了以下代码。
    System.Diagnostics.Process capp = new System.Diagnostics.Process();
    capp.StartInfo.UseShellExecute = false;
    capp.StartInfo.RedirectStandardOutput = true; 
    capp.StartInfo.RedirectStandardError = true;
    capp.EnableRaisingEvents = false;
    capp.StartInfo.FileName = "app.exe";
    capp.StartInfo.Arguments = "-i -v -mj";
    capp.Start();

    consoleOutput = capp.StandardOutput.ReadToEnd() + capp.StandardError.ReadToEnd();
    if (!capp.WaitForExit(10000)) capp.Kill(); 

如果外部应用程序能够正常工作,那么完成任务所需的时间不到10秒钟。但是,如果由于某种原因停止/挂起,即使使用

    if (!capp.WaitForExit(10000)) capp.Kill(); 

正如其他主题所建议的那样,它继续工作。但在我的情况下,上述行似乎根本无法使用,我猜这与我读取StandardOutput和StandardError有关。如何修复我的代码,使输出读取和WaitForExit()一起工作呢?

1个回答

4
如果您不总是从 两者StandardOutputStandardError 中读取,缓冲区可能会填满,导致进程阻塞。
您首先尝试读取 StandardOutput 直到结束。您运行的进程可能会将大量数据写入 StandardError 直到被阻塞并且无法再写入。然后,此结果导致您的 应用程序阻塞,因为在进程关闭其StandardOutput 之前,它甚至没有开始从StandardError 中读取。这会创建死锁,两个进程都不会继续执行。
我建议您使用我在这里发布的解决方案。它使用异步读取来从 StandardOutputStandardError 中读取数据,避免了死锁。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接