Struct Struct - 1 month ago 5
C# Question

Deadlock in System.Diagnostic.Process

I have a small console application and I want to read the output in C#. Therefore I've created this code snippet. The command prompt opens, but nothing is displayed.

System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
process.StartInfo.FileName = DirectoryPath + "Test.exe";
process.StartInfo.Arguments = "-showAll";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.WaitForExit(2000);
String strOutput = process.StandardOutput.ReadToEnd();


If I remove
UseShellExecute
,
RedirectStandardOutput
and the last line, the command prompt opens and the
Test.exe
is shown, but I need the output as String and so I have to use these attributes to read the
StandardOutput


I've also tried to set a timeout of 2 seconds (
process.WaitForExit(2000)
), but the empty command prompt does not close after 2 seconds.

If I close the empty command prompt manually in debug mode, the variable strOutput has my requested information.

Answer

To avoid deadlock you have to read the output stream before you wait to exit. So try :

    System.Diagnostics.Process process = new System.Diagnostics.Process();
    process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
    process.StartInfo.FileName = DirectoryPath + "Test.exe";
    process.StartInfo.Arguments = "-showAll";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.Start();
    String strOutput = process.StandardOutput.ReadToEnd();
    process.WaitForExit();
Comments