2011年5月29日 星期日

[C#] Access is denied - 除錯心得

NET stack trace:
System.ComponentModel.Win32Exception: Access is denied
at System.Diagnostics.NtProcessManager.GetModuleInfos(
Int32 processId, Boolean firstModuleOnly)
at System.Diagnostics.NtProcessManager.GetFirstModuleInfo(
Int32 processId)
at System.Diagnostics.Process.get_MainModule()

My code snippet:
  process.Kill();
process.WaitForExit();
logger.Info(process.MainModule.FileName + " is killed.");

發現問題了嗎?The Kill() method executes asynchronously. After calling the Kill() method, call the WaitForExit() method to wait for the process to exit. 所以問題出在第三行: process.MainModule.FileName. 當 process 死掉之後,.NET 的 Process object 也會一起死掉。

因此正確的 code snippet 是:
  String process_filename = process.MainModule.FileName;
process.Kill();
process.WaitForExit();
logger.Info(process_filename + " is killed.");

這樣就能解決 Access is denied 的問題。

沒有留言:

張貼留言