重定向输出时 ResGen.exe 卡住
我尝试从 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 时,它可以正常工作。
我做错了什么?
I try to redirect standard output from ResGen.exe. I use following code
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();
It stuck on p.WaitForExit. When I turn off output stream redirection and do not read StandardOutput it works correctly.
What do I do wrong ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
读取流后,您需要等待进程结束,否则代码中会出现死锁。
问题是您的父进程正在阻塞等待子进程完成,而子进程正在等待父进程读取输出,因此出现死锁。
这里是关于问题。
像这样更改代码应该可以避免死锁:
You would need to wait for the process to end after reading the stream, otherwise you have a deadlock in your code.
The problem is that your parent process is blocking waiting for the child process to finish, and the child process is waiting for the parent process to read the output, hence you have a deadlock.
Here is a good and detailed description of the problem.
Changing your code like this should avoid the deadlock:
底线似乎是
p.WaitForExit
的位置不正确;仅应在从流中读取所需内容后才进行此方法调用。来自 MSDN:
另请注意,您使用
StreamReader sr = p.StandardOutput
在这里是多余的,因为当设置message
的值时,您可以使用p.StandardOutput.ReadToEnd();
访问流> - 请注意p.StandardOutput
,而不是sr.ReadToEnd()
。The bottom line would seem to be that the placement of
p.WaitForExit
is incorrect; this method call should be made only after reading what you want from the stream.From MSDN:
Also note that your use of
StreamReader sr = p.StandardOutput
is redundant here since when the value ofmessage
is set you access the stream usingp.StandardOutput.ReadToEnd();
- note thep.StandardOutput
as opposed tosr.ReadToEnd()
.