C# 重定向输出时ResGen.exe会阻塞
我尝试从ResGen.exe重定向标准输出。我使用以下代码C# 重定向输出时ResGen.exe会阻塞,c#,process,C#,Process,我尝试从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.
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时,它工作正常
我做错了什么?在读取流之后,您需要等待进程结束,否则代码中会出现死锁。 问题是父进程正在阻塞,等待子进程完成,而子进程正在等待父进程读取输出,因此出现了死锁 是对问题的良好和详细的描述 这样更改代码可以避免死锁:
StreamReader sr = p.StandardOutput;
string message = p.StandardOutput.ReadToEnd();
p.WaitForExit();
底线似乎是
p.WaitForExit
的位置不正确;只有在从流中读取所需内容后,才能进行此方法调用
发件人:
还请注意,您在此处使用
StreamReader sr=p.StandardOutput
是多余的,因为当设置message
的值时,您可以使用p.StandardOutput.ReadToEnd()访问流代码>-注意p.StandardOutput
与sr.ReadToEnd()
相反。读取输出,而不是“写入输出”。输出缓冲区很小,通常为2千字节。ReadToEnd在WaitForExit足够好之前,“结束”不会发生,直到程序结束。谢谢。不过,如果你需要将应用程序的输出实时写入用户界面,这个问题会变得更加复杂,但这并不能解决这个问题。
// 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();