首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ResGen.exe在重定向输出时阻塞

ResGen.exe在重定向输出时阻塞
EN

Stack Overflow用户
提问于 2011-03-20 06:47:27
回答 2查看 693关注 0票数 3

我尝试重定向来自ResGen.exe的标准输出。我使用以下代码

代码语言:javascript
复制
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时,它可以正常工作。

我做错了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-03-20 07:38:44

在读取流之后,您需要等待进程结束,否则您的代码中会出现死锁。问题是您的父进程正在阻塞以待子进程完成,而子进程正在等待父进程读取输出,因此出现了死锁。

Here是对该问题的一个很好且详细的描述。

像这样修改你的代码可以避免死锁:

代码语言:javascript
复制
StreamReader sr = p.StandardOutput;
string message = p.StandardOutput.ReadToEnd();
p.WaitForExit();
票数 5
EN

Stack Overflow用户

发布于 2011-03-20 07:52:02

底线似乎是p.WaitForExit的位置不正确;只有在从流中读取您想要的内容之后,才应该调用此方法。

来自MSDN

代码语言:javascript
复制
 // 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();

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5365449

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档