[英]How can I verify if a Windows Service is running
I have an application in C# (2.0 running on XP embedded) that is communicating with a 'watchdog' that is implemented as a Windows Service.我有一个 C# 应用程序(在 XP 嵌入式上运行的 2.0),它与作为 Windows 服务实现的“看门狗”进行通信。 When the device boots, this service typically takes some time to start.当设备启动时,此服务通常需要一些时间才能启动。 I'd like to check, from my code, if the service is running.我想从我的代码中检查服务是否正在运行。 How can I accomplish this?我怎样才能做到这一点?
I guess something like this would work: 我猜这样的事情会起作用:
Add System.ServiceProcess
to your project references (It's on the .NET tab). 将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";
}
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. 编辑:还有一个sc.WaitforStatus()
方法,它采用所需的状态和超时,从未使用它,但它可能适合您的需要。
Edit: Once you get the status, to get the status again you will need to call sc.Refresh()
first. 编辑:获得状态后,要再次获取状态,您需要先调用sc.Refresh()
。
Reference: ServiceController object in .NET. 参考:.NET中的ServiceController对象。
请查看.NET中的ServiceController对象。
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. 您可以将您的服务与循环中的service.name属性进行比较,并获得您的服务状态。 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 有关详细信息,请访问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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.