【问题标题】:How to use Process.WaitForExit如何使用 Process.WaitForExit
【发布时间】:2011-09-14 20:32:08
【问题描述】:

我正在调用一个“有时”在 VB.NET 中工作的第 3 部分应用程序(它是一个自托管的 WCF)。但有时第 3 方应用程序会永远挂起,所以我为它添加了一个 90 秒计时器。问题是,我怎么知道事情是否超时?

代码如下:

Dim MyProcess as System.Diagnostics.Process = System.Diagnostics.Process.Start(MyInfo)
MyProcess.WaitForExit(90000)

我想做的是这样的

If MyProcess.ExceededTimeout Then
    MyFunction = False
Else
    MyFunction = True
End If

有什么想法吗?

谢谢,

杰森

【问题讨论】:

    标签: vb.net wcf process waitforexit


    【解决方案1】:

    过去存在已知问题,即在使用 WaitForExit 时应用会冻结。

    你需要使用

    dim Output as String = MyProcess.StandardOutput.ReadToEnd()
    

    打电话之前

    MyProcess.WaitForExit(90000)
    

    参考微软的sn-p:

    // Start the child process.
     Process p = new Process();
     // Redirect the output stream of the child process.
     p.StartInfo.UseShellExecute = false;
     p.StartInfo.RedirectStandardOutput = true;
     p.StartInfo.FileName = "Write500Lines.exe";
     p.Start();
     // Do not wait for the child process to exit before
     // reading to the end of its redirected stream.
     // p.WaitForExit();
     // Read the output stream first and then wait.
     string output = p.StandardOutput.ReadToEnd();
     p.WaitForExit();
    

    http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx

    【讨论】:

    • 可能会发生此类挂起,具体取决于环境。我有一个内置的进程运行器,它可以在 Web、控制台或 Windows 服务环境中执行。在我的情况下,只有控制台环境成功完成(并触发了 Exited 事件)。一旦我开始读取流(同步和异步),进程在所有三个环境中都按预期退出。
    【解决方案2】:

    检查方法返回值 - http://msdn.microsoft.com/en-us/library/ty0d8k56.aspx - 如果调用超时,则返回 False。

    【讨论】:

      【解决方案3】:
      if(process.WaitForExit(timeout)) {
          // user exited
      } else {
          // timeout (perhaps process.Kill();)
      }
      

      Async process start and wait for it to finish

      【讨论】:

      • 请用文字解释你的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      • 2016-08-01
      • 2010-10-27
      • 1970-01-01
      • 2011-10-28
      • 1970-01-01
      相关资源
      最近更新 更多