System.Diagnostic.Process 中的死锁

Deadlock in System.Diagnostic.Process

我有一个小型控制台应用程序,我想读取 C# 中的输出。因此我创建了这个代码片段。命令提示符打开,但未显示任何内容。

System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
process.StartInfo.FileName = DirectoryPath + "Test.exe";
process.StartInfo.Arguments = "-showAll";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.WaitForExit(2000);
String strOutput = process.StandardOutput.ReadToEnd();

如果我删除 UseShellExecuteRedirectStandardOutput 和最后一行,命令提示符将打开并显示 Test.exe,但我需要输出为字符串,所以我必须使用这些属性来读取 StandardOutput

我也尝试过将超时设置为 2 秒 (process.WaitForExit(2000)),但是空命令提示符在 2 秒后没有关闭。

如果我在调试模式下手动关闭空命令提示符,变量 strOutput 有我请求的信息。

为避免死锁,您必须在等待退出之前读取输出流。所以试试 :

    System.Diagnostics.Process process = new System.Diagnostics.Process();
    process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
    process.StartInfo.FileName = DirectoryPath + "Test.exe";
    process.StartInfo.Arguments = "-showAll";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.Start();
    String strOutput = process.StandardOutput.ReadToEnd();
    process.WaitForExit();