C# 如何验证 Windows 服务是否正在运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/178147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I verify if a Windows Service is running
提问by edosoft
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. 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?
我有一个 C# 应用程序(在 XP 嵌入式上运行的 2.0),它与作为 Windows 服务实现的“看门狗”进行通信。当设备启动时,此服务通常需要一些时间才能启动。我想从我的代码中检查服务是否正在运行。我怎样才能做到这一点?
采纳答案by Carl
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: ServiceControllerobject in .NET.
参考:.NET 中的ServiceController对象。
回答by rhatwar007
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.aspxalso http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx
您可以将您的服务与循环内的 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