为什么hasExited抛出'System.ComponentModel.Win32Exception'?

时间:2009-04-21 21:34:00

标签: c# process

我可以使用ShellExecuteEx成功运行新进程,但是如果我访问HasExited属性,则抛出Win32Exception。什么是此异常,如何检查进程是否还活着?

ShellExecuteEx(ref info);
clientProcessId = NativeMethods.GetProcessId(info.hProcess);
Process clientProcess = Process.GetProcessById((int)clientProcessId);

if (clientProcess.HasExited) //<---- throws Win32Exception, but the process is alive! I can see its window
{
   //run new one
}

由于

3 个答案:

答案 0 :(得分:0)

有关信息,您是否将fMask设置为SEE_MASK_NOCLOSEPROCESS,以便hProcess有效?

另外,为什么要P / Invoke到ShellExecuteEx,为什么不使用ProcessStartInfo的Process.Start,它会为你处理ShellExecuteEx?

编辑:由于你正在运行runas,你只能在句柄上获得SYNCHRONIZE访问,而不是PROCESS_QUERY_INFORMATION访问,因此GetExitCodeProcess失败,导致hasEnded抛出Win32异常。

作为一种解决方法,您可以使用超时为零的P / Invoke WaitForSingleObject来查看进程是否已退出。

答案 1 :(得分:0)

我今天遇到了这个问题。还有另一种解决方案。 WaitForExit函数在另一个用户环境中运行正常。 因此,如果您使用runas来提升进程权限,则可以使用此函数查询进程状态。

答案 2 :(得分:-1)

可能会抛出错误,因为该对象不再存在,因此您检查被销毁的对象

在处理图片时vb中出现了类似的问题

function openimg(imgpath)
img = get image from path
return img
end function

由于某种原因不能正确返回图像

相反,该行必须是

返回img.clone()以正确返回图像

然而那是我的例子