在 onStart() 方法中停止 Windows 服务 [英] stop windows service in onStart() method
问题描述
我想在客户没有许可证时在 onStart()
方法中停止 Windows 服务.我使用 service.Stop()
,但它不起作用.
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 ");
}
}
推荐答案
您不能从同一服务的 OnStart
方法中停止该服务.
You cannot stop a service from within the OnStart
method of that same service.
ServiceController.Stop
方法内部调用 ControlService
(或者它的 Ex
对应物).请注意,此函数可能失败的原因之一是:
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由于服务状态为SERVICE_STOPPED、SERVICE_START_PENDING或SERVICE_STOP_PENDING,因此无法将请求的控制代码发送到服务.
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.
好吧,猜猜看 - 当您在 OnStart
方法中时,您的服务状态是 SERVICE_START_PENDING
.
Well, guess what - when you're inside your OnStart
method, the state of your service is SERVICE_START_PENDING
.
处理这种情况的正确方法是通知任何其他线程您可能已经开始让它们退出,然后退出您的 OnStart
方法.服务控制管理器会注意到该进程已退出并将您的服务状态恢复为 SERVICE_STOPPED
.它还可以通知交互式用户服务已启动然后停止"或类似的话.
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.
这篇关于在 onStart() 方法中停止 Windows 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!