【发布时间】:2011-08-31 19:05:42
【问题描述】:
我编写了一些代码来与经常挂起的控制台应用程序进行交互(由于有错误的 COM 互操作,我无法控制)。我的方法包括在超时后调用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..)? -
你在什么操作系统上运行,进程提升了吗?