Process MainModule - 我可以避免 Win32 异常吗?

Process MainModule - can I avoid Win32 exception?

我正在枚举进程以查找 excel.exe 是否为 运行ning(例如)。 我从系统服务等方面得到了很多Win32Exception

Process[] pps = Process.GetProcesses();
foreach (var process in pps)
{
    string module = null;
    try
    {
        module = process.MainModule?.FileName;
    }
    catch (Win32Exception)
    {
        continue;
    }

这使枚举成为 运行 500 毫秒而不是 10 毫秒。

有没有办法在不触发异常的情况下判断进程是否有主模块?或任何其他查找进程 exe 路径的方法?

当您尝试执行您的 OS 不允许的操作时,会发生此异常。您可以检查 NativeErrorCode 属性 以查看有关异常的更多详细信息。

您可以找到解决方案 here 来处理该问题。

正如@steeeve 在评论中提到的,如果性能是您的唯一标准,您可以使用 GetProcessByName