What is the correct order for calling the process class with WaitForExit?
I'm having a bit of trouble de-ciphering the msdn documentation.
I want to call the process class. If the process that the process class calls exits I want my code to exit but I want the "StandardOutput" and the "StandardError" to be written to a log file.
If the process that the process class calls hangs (and doesnt exit) I want my code to timeout and close the process after a certain timeout 'time' but I still want the "StandardOutput" and the "StandardError" to be written to a log file.
So I have this as my code:
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());
开发者_如何学Go }
catch (Exception ex)
{
//nothing to do with this yet
}
finally
{
try
{
p.Kill();
}
catch { }
}
}
Is this the right way of doing things?
Not exactly, you need a timer to set the timeout. This code might help you:
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();
}
Good luck!
精彩评论