用WaitForExit调用流程类的正确顺序是什么?
问题描述:
我在解密msdn文档时遇到了一些麻烦。用WaitForExit调用流程类的正确顺序是什么?
我想调用进程类。如果进程类调用的进程退出,我希望我的代码退出,但我希望将“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 { }
}
}
这是做事的正确方法吗?
答
不完全是,您需要一个计时器来设置超时。此代码可能会对您有所帮助:
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();
}
祝您好运!
我不明白这个代码:-(我不知道第8行的含义是什么,这是一个匿名方法吗? – Exitos 2011-04-12 10:08:16
那么,你可以把它作为一个普通的函数,只要把它拿出来。 – Homam 2011-04-12 11:50:36