如何验证 Windows 服务是否正在运行

本文关键字:是否 服务 运行 Windows 何验证 验证 | 更新日期: 2023-09-27 17:47:21

我有一个C#应用程序(2.0在XP嵌入式上运行),它正在与作为Windows服务实现的"看门狗"进行通信。当设备启动时,此服务通常需要一些时间才能启动。我想从我的代码中检查服务是否正在运行。我怎样才能做到这一点?

如何验证 Windows 服务是否正在运行

我想这样的东西会起作用:

System.ServiceProcess添加到项目引用(位于".NET"选项卡上)。

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.WaitforStatus(),它采用所需的状态和超时,从未使用它,但它可能适合您的需求。

编辑:获得状态后,要再次获取状态,您需要先致电sc.Refresh()

参考:.NET 中的服务控制器对象。

在这里,您可以获得所有可用的服务及其在本地计算机中的状态。

ServiceController[] services = ServiceController.GetServices();
foreach(ServiceController service in services)
{
    Console.WriteLine(service.ServiceName+"=="+ service.Status);
}

您可以将服务与循环内 service.name 属性进行比较,您将获得服务的状态。有关详细信息,请参阅 http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx另 http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx