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

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

198816 次浏览

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

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";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

Here you get all available services and their status in your local machine.

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

You can Compare your service with service.name property inside loop and you get status of your service. For details go with the http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx also http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx