I want to stop windows service in onStart()
method when customer doesn't have a license. I use service.Stop()
, but it does not work.
protected override void OnStart(string[] args)
{
try
{
_bridgeServiceEventLog.WriteEntry("new OnStart");
if (LicenseValidetor.ValidCountAndTypeDevices())
{
WsInitializeBridge();
}
else
{
service = new ServiceController("BridgeService");
service.Stop();
_bridgeServiceEventLog.WriteEntry("LicenseValidetor Error");
}
_bridgeServiceEventLog.WriteEntry("end Start");
}
catch (Exception e)
{
_bridgeServiceEventLog.WriteEntry("error In onstart method ");
}
}
You cannot stop a service from within the OnStart
method of that same service.
The ServiceController.Stop
method internally calls ControlService
(or it's Ex
counterpart). Notice that one of the reasons that this function can fail is:
ERROR_SERVICE_CANNOT_ACCEPT_CTRL The requested control code cannot be sent to the service because the state of the service is SERVICE_STOPPED, SERVICE_START_PENDING, or SERVICE_STOP_PENDING.
Well, guess what - when you're inside your OnStart
method, the state of your service is SERVICE_START_PENDING
.
The correct way to cope with this situation is to signal any other threads that you may have started to have them exit, and then to exit your OnStart
method. The service control manager will notice that the process has exited and revert your service status to SERVICE_STOPPED
. It may also notify an interactive user that "The service started and then stopped" or words to that effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With