Learner
Learner

Reputation: 4751

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?

Upvotes: 1

Views: 2002

Answers (1)

Learner
Learner

Reputation: 4751

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!

Upvotes: 1

Related Questions