我已經寫了一些代碼來與定期掛起的控制檯應用程序進行交互(由於錯誤的COM interop我無法控制)。我的方法包括在超時後調用Process.Kill()
,但它似乎並沒有終止進程 - 它仍然出現在任務管理器中。這段代碼有什麼問題嗎?Process.Kill不能查殺進程
private static string CallBuggyConsoleApp(string path, string ext) {
var startInfo = new ProcessStartInfo {
FileName = ConsoleAppPath,
Arguments = String.Format("\"{0}\" {1}", path, ext),
UseShellExecute = 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));
}
}
爲什麼'proc.Start'執行兩次? proc.Kill行是否真的執行(使用調試器進行檢查)?什麼樣的COM組件是這樣的(COM/COM +/DCOM ..)? – Yahia
你在運行什麼操作系統,進程是否升級? – TheCodeKing