进程的终止方法不起作用
我正在尝试测试以下代码片段。
static void StartAndKill()
{
Process ieProc = Process.Start("iexplore.exe", "www.apress.com");
Console.WriteLine("--> Hit enter to kill {0}\t", ieProc.ProcessName);
Console.ReadLine();
try
{
Console.WriteLine(ieProc.Id);
ieProc.Kill();
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
这应该会杀死 Internet Explorer 窗口并将其关闭。相反,我得到一个异常:
Cannot process request because the process (7256) has exited.
此行为的逻辑解释是什么?
I am trying to test the following code snippet.
static void StartAndKill()
{
Process ieProc = Process.Start("iexplore.exe", "www.apress.com");
Console.WriteLine("--> Hit enter to kill {0}\t", ieProc.ProcessName);
Console.ReadLine();
try
{
Console.WriteLine(ieProc.Id);
ieProc.Kill();
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
This should kill the internet explorer window and close it. Instead I get an exception that says:
Cannot process request because the process (7256) has exited.
What is the logical explanation for this behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果 iexplore 进程已经在运行(检查任务管理器),则 Process.Start 可能会使用现有进程 - 但您返回的进程 ID 不是针对该现有进程,而是一个启动然后退出的虚拟进程。您可以枚举现有的 iexplore 进程并检查其标题以找到正确的进程,然后获取其进程 ID 并终止它。
If the iexplore process is already running (check Task Manager), then Process.Start may use the existing process - but the process id you get back is not for this existing process, but a dummy process that starts and then exits. You could enumerate the existing iexplore processes and check their titles to find the correct one, and then get its process id and kill it.
该错误消息具有误导性。该进程没有被终止的真正原因是 Windows 7 上的管理权限不是默认的。如果我使用“以管理员身份运行”打开命令提示符,代码将执行其应该执行的操作。我将结束这个问题。
感谢所有回复的人。
The error message is misleading. The real reason why the process doesn't get killed is administrative privs on Windows 7 are not defaulted. If I open a command prompt by using "Run as administrator", the code does what it is supposed to do. I will move to close this question.
Thanks to all those who responded.