2011-08-31 38 views
2

我已經寫了一些代碼來與定期掛起的控制檯應用程序進行交互(由於錯誤的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)); 
    } 
} 
+1

爲什麼'proc.Start'執行兩次? proc.Kill行是否真的執行(使用調試器進行檢查)?什麼樣的COM組件是這樣的(COM/COM +/DCOM ..)? – Yahia

+0

你在運行什麼操作系統,進程是否升級? – TheCodeKing

回答

2

在代碼的內部部分,您在第一次拋擲時不會調用Kill

一般Exception不應該用在投擲中,更常用的是拋出一些派生類,比如ApplicationException或其他更專業的類。

除此之外,你爲什麼要打兩次?它會如何表現只調用一次啓動?你看到有什麼不同嗎?

+0

啊,那可能就是它!我沒有注意到我正在調用'Start'兩次。徘徊的進程很可能並不是被殺的人。 – Daniel

+0

沒有問題。我也會嘗試使用相同的代碼,但啓動另一個應用程序,例如notepad.exe,只是爲了確保它可以像其他可執行文件一樣運行... –

+0

可能是一個好主意。謝謝。是的,刪除其他調用'開始'似乎修復了它。我想我正在尋找一個接受'ProcessStartInfo'的構造函數,最後調用'Start',並且忘記了它。在接線事件處理程序後,我會自動將第二個調用插入'Start'。 – Daniel