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

时间:2011-04-11 16:49:02

标签: c# .net-4.0 process

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

我想调用进程类。如果进程类调用的进程退出,我希望我的代码退出,但我希望将“StandardOutput”和“StandardError”写入日志文件。

如果进程类调用的进程挂起(并且没有退出),我希望我的代码超时并在某个超时“时间”之后关闭进程,但我仍然希望写入“StandardOutput”和“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 { }
    }
}

这是正确的做事方式吗?

1 个答案:

答案 0 :(得分:0)

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

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();
}
祝你好运!