繁体   English   中英

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 ,但我需要输出为String,因此我必须使用这些属性来读取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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM