gpt4 book ai didi

c# - 在 onStart() 方法中停止 Windows 服务

转载 作者:太空狗 更新时间:2023-10-30 00:43:10 24 4
gpt4 key购买 nike

当客户没有许可证时,我想在 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 对应物)。请注意,此功能可能失败的原因之一是:

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


处理这种情况的正确方法是向任何其他线程发出信号,表明您可能已经开始让它们退出,然后退出您的 OnStart 方法。服务控制管理器会注意到该进程已退出并将您的服务状态恢复为 SERVICE_STOPPED。它还可以通知交互式用户“服务启动然后停止”或类似的字样。

关于c# - 在 onStart() 方法中停止 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12068492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com