【问题标题】:Process.StandardOutput.ReadToEnd() vs Process.WaitForExit()Process.StandardOutput.ReadToEnd() 与 Process.WaitForExit()
【发布时间】:2018-12-21 08:59:36
【问题描述】:

我有一个 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

【问题讨论】:

    标签: c# process waitforexit


    【解决方案1】:
    process.StandardOutput.ReadToEnd();
    

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

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

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

    Stack Overflow 上的这篇文章有 some good examples of both these cases

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 2010-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多