使用WaitForExit调用流程类的正确顺序是什么?

本文关键字:顺序 是什么 WaitForExit 调用 程类 使用 | 更新日期: 2023-09-27 17:50:05

我在解密msdn文档时遇到了一点麻烦。

我想调用进程类。如果进程类调用的进程退出,我希望我的代码退出,但我希望"StandardOutput"answers"StandardError"被写入日志文件。

如果进程类调用的进程挂起(并且不退出),我希望我的代码超时并在一定的超时'时间'后关闭进程,但我仍然希望将"StandardOutput"answers"StandardError"写入日志文件。

我的代码是这样的:

using (Process p = new Process())
{
    p.StartInfo.FileName = exePathArg;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.Arguments = argumentsArg;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.CreateNoWindow = true;
    try
    {
        p.Start();
        p.WaitForExit(timeToWaitForProcessToExit);
        StreamReader standardOutput = p.StandardOutput;
        StreamReader standardError = p.StandardError;
        retDirects.Add("StandardOutput", standardOutput.ReadToEnd());
        retDirects.Add("StandardError", standardError.ReadToEnd());    
    }
    catch (Exception ex)
    {
        //nothing to do with this yet
    }
    finally
    {
        try
        {
            p.Kill();
        }
        catch { }
    }
}

这是正确的做法吗?

使用WaitForExit调用流程类的正确顺序是什么?

不完全是这样,您需要一个计时器来设置超时。下面的代码可能会对您有所帮助:

Process process = Process.Start(startInfo);
process.EnableRaisingEvents = true;
bool execTimeout = false;
// this call back will be called when timer ticks, Timeout for process.
TimerCallback callBack = (_process) =>
{
    // if the process didn't finish exexuting
    // and the timeout has reached 
    // then kill the process.
    if (!(_process as Process).HasExited)
    {
        execTimeout = true;
        (_process as Process).Kill();
    }
};
int timeout = 4000; // 4 seconds
System.Threading.Timer timer = new System.Threading.Timer(callBack, 
                                     process, timeout, Timeout.Infinite);
// block untill finishing executing [Sync calling]
process.WaitForExit();
// Disable the timer. because the process has finished executing.
timer.Change(Timeout.Infinite, Timeout.Infinite);
// if the process has finished by timeout [The timer which declared above]
// or finished normally [success or failed].
if (execTimeout)
{
    // Write in log here
}
else
{
    string standardOutput = process.StandardOutput.ReadToEnd();
    string standardError = process.StandardError.ReadToEnd();
}

祝你好运!