简体   繁体   中英

ServiceController.Stop() fails to stop service

I have a windows service which I'm trying to stop progrmatically using 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.

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() . The ServiceController.Stop() was called from the OnStart() method itself whenever validation fails! 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.

I changed the logic and now i dont call ServiceBase.Run() method (which gives call to OnStart() ) if necessary configuration is missing.

The legacy code was trying to Stop the service from its Start method!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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