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
OnStartmethod of that same service.The
ServiceController.Stopmethod internally callsControlService(or it’sExcounterpart). Notice that one of the reasons that this function can fail is:Well, guess what – when you’re inside your
OnStartmethod, the state of your service isSERVICE_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
OnStartmethod. The service control manager will notice that the process has exited and revert your service status toSERVICE_STOPPED. It may also notify an interactive user that “The service started and then stopped” or words to that effect.