I want my logic to be correct. I want to start a process in timeout seconds, if it runs longer, it should be killed immediately.
The completed flag should reliably indicate whether the process completed as intended, for example, has not been killed, and also not a failure or throwing an exception.
Also, I'm not sure if the check on process.HasExited correct. If process.WaitForExit() returns false and Kill() succeeds, will process.HasExited always be true? That would be my guess, but I wanted to confirm. Also, what if something can be done if kill () is other than what you register?
using (process = new Process()) { process.EnableRaisingEvents = true; process.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived); process.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived); process.Exited += new EventHandler(OnExited); process.StartInfo = startInfo; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (!process.WaitForExit(timeout)) { try { process.Kill(); } catch (Exception e) { LogError(e, MethodBase.GetCurrentMethod()); } finally { this.completed = false; } } else { if (process.HasExited) { this.code = process.ExitCode; this.completed = true; } else { this.completed = false; } } }
source share