0

我有一个 Windows 服务调用控制台应用程序并读取控制台输出以确定状态。

在调用 StandardOutput.ReadToEnd() 后,我在有时间限制的情况下调用 WaitForExit()。

问题是如果控制台应用程序花费的时间超过 WaitForExit() 的时间限制,那么 ReadToEnd() 会阻塞直到可执行文件退出,从而使 WaitForExit() 变得多余?

      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://docs.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
4

1 回答 1

0
process.StandardOutput.ReadToEnd();

此调用是一个阻塞调用,将永远等待,直到所有输出在被调用的进程中刷新。

这意味着不需要您的 process.WaitForExit 调用。您真正需要做的是以异步方式读取输出流,以便您可以选择等待输出完成的时间。

您还需要注意其他流,例如 StandardError,它也可能包含输出。

这篇关于 Stack Overflow 的文章在这两种情况下都有一些很好的例子

于 2018-12-21T09:59:08.807 回答