我尝试重定向来自ResGen.exe的标准输出。我使用以下代码
ProcessStartInfo psi = new ProcessStartInfo( "resxGen.exe" );
psi.CreateNoWindow = true;
psi.Arguments = sb.ToString();
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
Process p = Process.Start( psi );
p.WaitForExit();
StreamReader sr = p.StandardOutput;
string message = p.StandardOutput.ReadToEnd();它在p.WaitForExit上卡住了。当我关闭输出流重定向并且不读取StandardOutput时,它可以正常工作。
我做错了什么?
发布于 2011-03-20 07:38:44
在读取流之后,您需要等待进程结束,否则您的代码中会出现死锁。问题是您的父进程正在阻塞以待子进程完成,而子进程正在等待父进程读取输出,因此出现了死锁。
Here是对该问题的一个很好且详细的描述。
像这样修改你的代码可以避免死锁:
StreamReader sr = p.StandardOutput;
string message = p.StandardOutput.ReadToEnd();
p.WaitForExit();发布于 2011-03-20 07:52:02
底线似乎是p.WaitForExit的位置不正确;只有在从流中读取您想要的内容之后,才应该调用此方法。
来自MSDN:
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();还要注意,在这里使用StreamReader sr = p.StandardOutput是多余的,因为当设置了message的值时,您将使用sr.ReadToEnd().而不是message来访问流-请注意p.StandardOutput.ReadToEnd();
https://stackoverflow.com/questions/5365449
复制相似问题