检查是否有来自 Windows 服务的进程 运行

Check if there's a process running from Windows Service

目前,我正在使用:

private bool IsProcessRunning(string ProcessName)
{
    foreach(Process clsProcess in Process.GetProcesses())
    {
        if(clsProcess.ProcessName.Contains(ProcessName))
        {
            return true;
        }
    }
    return false;
}

这个 bool returns true 如果进程是 运行。这在 Console/WinForms 应用程序中工作正常,但当我尝试检查进程是否来自 Windows 服务时它不起作用。众所周知,Windows 服务在与其他应用程序不同的 SID 上 运行。那么,有谁知道如何检查应用程序是否 运行 在不同的会话中?

您可能想查看 ServiceController。不知道对你有没有帮助?

下面是如何使用它的示例

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
  case ServiceControllerStatus.Running:
    return "Running";
  case ServiceControllerStatus.Stopped:
    return "Stopped";
  case ServiceControllerStatus.Paused:
    return "Paused";
  case ServiceControllerStatus.StopPending:
    return "Stopping";
  case ServiceControllerStatus.StartPending:
    return "Starting";
  default:
    return "Status Changing";
}

如果需要重新获取状态,需要先刷新状态再查看

sc.Refresh()