C# 检查 Windows 服务是否正在运行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2324615/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:25:46  来源:igfitidea点击:

Check if a windows service is running?

c#windows-services

提问by user280154

I need to check whether my window service is running or not every 15 minutes or so.

我需要每 15 分钟左右检查一次窗口服务是否正在运行。

If it is not running, then how can I restart the windows service again?

如果它没有运行,那么如何再次重新启动 Windows 服务?

回答by fretje

You can check if a service is running with a ServiceController:

您可以使用ServiceController检查服务是否正在运行:

ServiceController sc = new ServiceController("servicename");

if  ((sc.Status.Equals(ServiceControllerStatus.Stopped)) ||
     (sc.Status.Equals(ServiceControllerStatus.StopPending)))
{
   // Start the service if the current status is stopped.
   sc.Start();
}  

Of course, you will need to call this from another service, or create it as a small program which you then can schedule to run every 15 minutes or so.

当然,您需要从另一个服务调用它,或者将其创建为一个小程序,然后您可以安排它每 15 分钟左右运行一次。

回答by Oded

If the service is not running, it cannot check itself.

如果服务未运行,则无法检查自身。

You will need to use a second service that does the checking.

您将需要使用进行检查的第二项服务。

回答by Rob van Groenewoud

You don't need an extra process to recover your service:

您不需要额外的过程来恢复您的服务:

If you want to be certain that your windows service is always running, check its properties in the Recovery tab. Set all failure actions to "Restart the Service" and set "Restart service after" to 0 minutes. The moment your service disappears it will be restarted immediately. Increase the timeout if it's ok to wait a bit longer before a restart is done:

如果您想确定您的 Windows 服务始终在运行,请在“恢复”选项卡中检查其属性。将所有失败操作设置为“重新启动服务”并将“重新启动服务之后”设置为 0 分钟。您的服务消失的那一刻,它将立即重新启动。如果可以在重新启动之前等待更长的时间,则增加超时时间:

Service Recovery settings http://www.robvangroenewoud.com/images/service_recovery.png

服务恢复设置 http://www.robvangroenewoud.com/images/service_recovery.png

回答by CoreTech

The built-in Windows Services Recovery functionality (see the screenshot in Rob's post above) will probably meet your needs. If not, I suggest trying Service Protector, which is designed to automatically keep your important Windows Services running 24/7.

内置的 Windows 服务恢复功能(请参阅上面 Rob 帖子中的屏幕截图)可能会满足您的需求。如果没有,我建议尝试Service Protector,它旨在自动保持重要的 Windows 服务 24/7 运行。