0

I have a windows service calling a console application and reads the console output to figure out the status.

I am calling WaitForExit() with a time limit after calling StandardOutput.ReadToEnd().

The question is in cases where the console application takes more time than the time limit for WaitForExit(), then will ReadToEnd() block till the executable has exited making WaitForExit() redundant ?

      Process process = new Process();
      process.StartInfo = new ProcessStartInfo
      {
          FileName = pathToExecutable,
          Arguments = args,
          UseShellExecute = false,
          RedirectStandardOutput = true,
          CreateNoWindow = true
      };
      process.Start();

      // Adding ReadToEnd() before the WaitForExit() call to prevent deadlocks in case Process buffer size becomes full
      // Ref: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.standardoutput?redirectedfrom=MSDN&view=netframework-4.5.2#remarks
      response = process.StandardOutput.ReadToEnd();

      process.WaitForExit(waitForExitInSeconds * 1000);
      process.Close();

      // Read response string and determine status
M22an
  • 1,242
  • 1
  • 18
  • 35

1 Answers1

0
process.StandardOutput.ReadToEnd();

This call is a blocking call and will wait forever till all the output is flushed in the process that is called.

This means your process.WaitForExit call is not needed. What you really need to do is read the output stream in an asynchronous manner so you can choose how long you wait around for the output to complete.

You also need to be aware of other streams like StandardError, which may also contain output.

This article here on Stack Overflow has some good examples of both these cases

Bigtoe
  • 3,372
  • 1
  • 31
  • 47