Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在onStart()方法中停止windows服务_C#_Windows Services - Fatal编程技术网

C# 在onStart()方法中停止windows服务

C# 在onStart()方法中停止windows服务,c#,windows-services,C#,Windows Services,当客户没有许可证时,我想在onStart()方法中停止windows服务。我使用了service.Stop(),但它不起作用 protected override void OnStart(string[] args) { try { _bridgeServiceEventLog.WriteEntry("new OnStart"); if (LicenseValidetor.ValidCountAndTypeDevices()) {

当客户没有许可证时,我想在
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
方法中停止该服务

该方法在内部调用(或它的
Ex
对应项)。请注意,此功能可能失败的原因之一是:

错误\u服务\u无法\u接受\u CTRL 无法将请求的控制代码发送到服务,因为服务的状态为服务停止服务开始、或服务停止

好吧,猜猜看-当您在
OnStart
方法中时,您的服务状态是
service\u START\u PENDING



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

我注意到您没有等待以确保该服务已实际停止,或者它是否在第一个实例中运行

这样做:-

protected override void OnStart(string[] args)
{
    try
    {
        _bridgeServiceEventLog.WriteEntry("new OnStart");
        if (LicenseValidetor.ValidCountAndTypeDevices())
        {
            WsInitializeBridge();
        }
        else
        {
            int time = 10000;

            TimeSpan timeout = TimeSpan.FromMilliseconds(time);

            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

            _bridgeServiceEventLog.WriteEntry("LicenseValidetor Error");
        }
        _bridgeServiceEventLog.WriteEntry("end Start");
    }
    catch (Exception e)
    {
        _bridgeServiceEventLog.WriteEntry("error In onstart method ");
    }
}
我想补充一点,“根本不雇佣任何工人”可能不起作用(或者我只是太愚蠢了)

我构建了一个服务,在OnStart代码中使用了try/catch(all)。由于我的.config文件中缺少一行,它在启动任何工作线程之前因IOException崩溃。异常跳过了我的线程启动器。我的代码没有启动任何线程。老实说

但服务并没有停止。我不知道为什么。作为一种不顾一切的措施,我重新提出了一个例外,这很有帮助


我仍然想知道企业库配置中的文件系统观察线程是否是问题所在。EntLib深入到我的代码中,作为一个实验将其删除,因此我没有进一步研究。

什么是
服务
?你确定这行代码被击中了吗?嗯。如果它与您正在运行的服务相同,那么只需退出
OnStart
方法而不让任何其他线程运行,就会停止该服务。您是否远程执行此操作?还是从客户端机器?