【问题标题】:stop windows service in onStart() method在 onStart() 方法中停止 Windows 服务
【发布时间】:2020-03-04 23:06:16
【问题描述】:

当客户没有许可证时,我想以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 ");
    }

}

【问题讨论】:

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

标签: c# windows-services


【解决方案1】:

您不能从同一服务的OnStart 方法中停止该服务。

ServiceController.Stop 方法在内部调用ControlService(或者它是Ex 对应)。请注意,此函数可能失败的原因之一是:

ERROR_SERVICE_CANNOT_ACCEPT_CTRL 请求的控制代码无法发送到服务,因为服务的状态是 SERVICE_STOPPEDSERVICE_START_PENDINGSERVICE_STOP_PENDING

好吧,你猜怎么着 - 当你在 OnStart 方法中时,你的服务状态是 SERVICE_START_PENDING


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

【讨论】:

    【解决方案2】:

    我想补充一点,“根本不启动任何工人”可能行不通(或者我可能只是很愚蠢;))。

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

    但是服务没有停止。我不知道为什么。作为一个绝望的措施,我重新抛出了异常,这有帮助。

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

    【讨论】:

      【解决方案3】:

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

      这样做:-

      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 ");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多