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();
Because
A deadlock condition can result if the parent process calls
p.WaitForExit
beforep.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?
In short this is what may happen:
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With