[英]Deadlock in System.Diagnostic.Process
I have a small console application and I want to read the output in C#. 我有一个小的控制台应用程序,我想读取C#中的输出。 Therefore I've created this code snippet. 因此我创建了此代码段。 The command prompt opens, but nothing is displayed. 命令提示符将打开,但不显示任何内容。
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();
If I remove UseShellExecute
, RedirectStandardOutput
and the last line, the command prompt opens and the Test.exe
is shown, but I need the output as String and so I have to use these attributes to read the StandardOutput
如果我删除UseShellExecute
, RedirectStandardOutput
和最后一行,命令提示符将打开并显示Test.exe
,但我需要输出为String,因此我必须使用这些属性来读取StandardOutput
I've also tried to set a timeout of 2 seconds ( process.WaitForExit(2000)
), but the empty command prompt does not close after 2 seconds. 我也尝试将超时设置为2秒( process.WaitForExit(2000)
),但空命令提示符在2秒后没有关闭。
If I close the empty command prompt manually in debug mode, the variable strOutput has my requested information. 如果我在调试模式下手动关闭空命令提示符,则变量strOutput具有我请求的信息。
To avoid deadlock you have to read the output stream before you wait to exit. 为避免死锁,您必须在等待退出之前读取输出流。 So try : 所以尝试:
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.