简体   繁体   中英

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM