如何判断进程ID是否存在

发布于 2024-08-07 11:43:34 字数 308 浏览 3 评论 0原文

我正在使用 C# .NET 2.0。我需要确定 PID 是否存在。我想出了以下代码:

private bool ProcessExists(int iProcessID)
{
    foreach (Process p in Process.GetProcesses())
    {
        if (p.Id == iProcessID)
        {
            return true;
        }
    }
    return false;
}

除了迭代所有进程之外,还有更好的方法吗?

I'm using C# .NET 2.0. I need to determine if a PID exists. I came up with the following code:

private bool ProcessExists(int iProcessID)
{
    foreach (Process p in Process.GetProcesses())
    {
        if (p.Id == iProcessID)
        {
            return true;
        }
    }
    return false;
}

Is there a better way to do this other than iterating all the processes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无远思近则忧 2024-08-14 11:43:34

快速注意:您无法确定除您自己的进程之外的进程是否正在运行。您只能看出它是在最近的某个时刻运行的。进程可以在任何给定时刻停止存在,包括您检查它是否具有匹配 ID 的确切时刻。

话虽这么说,这种类型的确定对于您的程序来说可能足够好,也可能不够好。这实际上取决于您想要做什么。

这是您编写的代码的缩写版本。

private bool ProcessExists(int id) {
  return Process.GetProcesses().Any(x => x.Id == id);
}

Quick Note: You can't ever determine if a process, other than your own, is running. You can only tell that it was running at some point in the recent past. A process can simply cease to exist at any given moment including the exact moment you check to see if it has a matching ID.

That being said, this type of determination may or may not be good enough for your program. It really depends on what you are trying to do.

Here is an abbreviated version of the code you wrote.

private bool ProcessExists(int id) {
  return Process.GetProcesses().Any(x => x.Id == id);
}
无妨# 2024-08-14 11:43:34

这里的风险在于:你从哪里获得进程 ID?如果它只是您之前保存的一个数字,则原始进程可能已终止,并且新进程可能是 使用相同的 ID 运行

你想实现什么目标?可能有更好的方法来实现您的实际目标。

The risky thing here is: Where did you get that Process ID from? If it's just a number you saved sometime earlier, the original process could have died and a new process could be running with the same ID.

What are you trying to accomplish? There may be a better way of achieving your actual goal.

罪#恶を代价 2024-08-14 11:43:34

如果进程不存在,System.Diagnostics.Process.GetProcessById(iProcessID) 将抛出 ArgumentException。虽然这不是检查进程是否存在的最佳方法,但希望这就是您正在寻找的。

System.Diagnostics.Process.GetProcessById(iProcessID) would throw ArgumentException if the process doesn't exist. Although that is not the best way to check if the process exists, but hopefully this is what you're looking for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文