简体   繁体   English

ServiceController.Stop()无法停止服务

[英]ServiceController.Stop() fails to stop service

I have a windows service which I'm trying to stop progrmatically using ServiceController.Stop() : 我有一个Windows服务,正在尝试使用ServiceController.Stop()停止进行编程:

ServiceController sc = new ServiceController(<ServiceName>);                    
sc.Stop();
sc.Refresh();

However, when I see this service in the Services list, its status still remains as "Started". 但是,当我在“服务”列表中看到该服务时,其状态仍保持为“已启动”。 If I call the method sc.WaitForStatus() to wait till the status is changed to "Stopped", then this status is never reached. 如果我调用方法sc.WaitForStatus()等待状态更改为“已停止”,则永远不会达到此状态。

What's going wrong? 怎么了

I think problem was with legacy code. 我认为问题在于遗留代码。

We need some configuration and the requirement is if configuration is missing in config file, service should not be started. 我们需要一些配置,要求是如果配置文件中缺少配置,则不应启动服务。 This validation was done in OnStart() . 该验证是在OnStart() The ServiceController.Stop() was called from the OnStart() method itself whenever validation fails! 每当验证失败时,就会从OnStart()方法本身调用ServiceController.Stop() I think that's why ServiceController.Stop() was not able to stop the service and I never got the status "Stopped" in WaitForStatus() method call. 我认为这就是为什么ServiceController.Stop()无法停止服务,并且在WaitForStatus()方法调用中我从未获得状态“ Stopped”的原因。

I changed the logic and now i dont call ServiceBase.Run() method (which gives call to OnStart() ) if necessary configuration is missing. 我更改了逻辑,现在如果缺少必要的配置, OnStart()调用ServiceBase.Run()方法(该方法调用OnStart() )。

The legacy code was trying to Stop the service from its Start method! 旧代码试图从其Start方法停止服务!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM