Process.Kill not killing process
I've written some code to interact with a console app that regularly hangs (due to buggy COM interop I have no control over). My method includes a call to Process.Kill()
after a timeout, but it doesn't seem to kill the process--it still appears in Task Manager. Is there something wrong with this code?
private static string CallBuggyConsoleApp(string path, string ext) {
var startInfo = new ProcessStartInfo {
FileName = ConsoleAppPath,
Arguments = String.Format("\"{0}\" {1}", path, ext),
UseShell开发者_如何学JAVAExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using (var proc = Process.Start(startInfo)) {
//The line above should be replaced with:
//using (var proc = new Process()) {
// proc.StartInfo = startInfo;
var output = new StringBuilder();
var error = new StringBuilder();
proc.OutputDataReceived += (_, args) => output.Append(args.Data);
proc.ErrorDataReceived += (_, args) => error.Append(args.Data);
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
if (proc.WaitForExit((int)ConsoleAppTimeout.TotalMilliseconds)) {
proc.WaitForExit();
if (proc.ExitCode != 0) {
throw new Exception(String.Format("Pid {0} exited at {1} with exit code {2} and the following error: {3}",
proc.Id, proc.ExitTime, proc.ExitCode, error.ToString()));
}
return output.ToString();
}
proc.CancelOutputRead();
proc.CancelErrorRead();
proc.Kill();
proc.WaitForExit();
throw new Exception(String.Format("Killed pid {0} at {1}", proc.Id, proc.ExitTime));
}
}
in the inner part of the code where you do the first throw you are not calling the Kill
.
in general Exception
should not be used in the throws, it's more usual to throw some derived classes of it like ApplicationException
or other more specialized ones.
beside this, why are you calling start twice? How would it behave calling start only once? Do you see any difference?
精彩评论