Process.StandardOutput.ReadToEnd()中的死锁问题; [英] DeadLock Issues in Process.StandardOutput.ReadToEnd();

查看:64
本文介绍了Process.StandardOutput.ReadToEnd()中的死锁问题;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已读,该部分内容代码可能导致死锁:

I read that this portion of code can cause deadlock:

 Process p = new Process();

 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 p.WaitForExit();
 string output = p.StandardOutput.ReadToEnd();

因为

如果发生以下情况,则可能导致死锁父进程调用 p.WaitForExit p.StandardOutput.ReadToEnd 和子进程写入足够的文本填充重定向的流.这父进程将无限期等待让子进程退出.这子进程将无限期等待让父母从全文中读取StandardOutput流.

A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardOutput.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardOutput stream.

但是我不太清楚为什么.我的意思是,在这种情况下,父进程是什么,子进程是什么?

But I don't quite why. I mean, in this case here, what's the parent process, and what's the child?

推荐答案

总之,这可能会发生:

应用程序A(上面的代码)启动子进程B并重定向标准输出.然后,A等待B进程退出.在A等待B退出的同时,B产生输出到输出流中(A已重定向).该流的缓冲区大小有限.如果缓冲区已满,则需要清空缓冲区,以便B能够继续写入缓冲区.由于A直到B退出才开始读取,因此您可能会遇到这样的情况,即B将等待清空输出缓冲区,而A将等待B退出.两者都在等待对方采取行动,您陷入僵局.

Application A (your code above) starts child process B and redirects standard output. Then A waits for the B process to exit. While A waits for B to exit, B produces output into the output stream (which A has redirected). This stream has a limited buffer size. If the buffer becomes full, it needs to be emptied in order to B to be able to continue writing into it. Since A is not reading until B has exited, you can end up in a situation where B will wait for the output buffer to be emptied, while A will wait for B to exit. Both are waiting for each other to take action, and you have a deadlock.

您可以尝试以下代码来演示该问题:

You can try the following code to demonstrate the problem:

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "cmd";
psi.Arguments = @"/c dir C:\windows /s";
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
Process p = Process.Start(psi);
p.WaitForExit();
string output = p.StandardOutput.ReadToEnd();

(很可能)这将导致输出流已满的情况,以便子进程(在这种情况下为"cmd" )将等待其清除,而上面的代码将等待 cmd 完成.

This will (moste likely) produce the situation where the output stream is full so that the child process (in this case "cmd") will wait for it to be cleared, while the code above will wait for cmd to finish.

这篇关于Process.StandardOutput.ReadToEnd()中的死锁问题;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆