当客户没有许可证时,我想以onStart()
方法停止Windows服务。我使用service.Stop()
,但是它不起作用。
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 ");
}
}
最佳答案
您无法通过同一服务的OnStart
方法停止该服务。
ServiceController.Stop
方法在内部调用 ControlService
(或Ex
对应项)。请注意,此功能可能失败的原因之一是:
好吧,猜猜是什么-当您在OnStart
方法内部时,服务的状态为SERVICE_START_PENDING
。
应对这种情况的正确方法是发信号通知您可能已经开始退出的任何其他线程,然后退出OnStart
方法。服务控制管理器将注意到该进程已退出,并将您的服务状态恢复为SERVICE_STOPPED
。它还可能会通知交互式用户“该服务已启动然后停止”或类似的字眼。