【问题标题】:How to reatart depend service if the main aervice failed and recovered in topshelf如果主服务失败并在 topshelf 中恢复,如何重新启动依赖服务
【发布时间】:2018-06-02 08:49:21
【问题描述】:

我有使用 topshelf 创建的 Windows 服务。有时此服务会停止。所以我希望它自动重启。所以我们在 topshelf 中有一个 onrecovery 选项。现在我的问题是当这个服务从失败中恢复时,我应该能够重新启动另一个服务,因为我的这个服务失败了。我将如何实现?

【问题讨论】:

    标签: c#-4.0 windows-services c#-7.0 topshelf


    【解决方案1】:

    首先,您应该让该服务依赖于该其他服务以确保它正在运行。

    在启动时,服务应向该服务发送命令以重新启动其逻辑。

    要让Topshelf 服务接收命令,服务类应该实现ServiceCustomCommand 或这样设置:

    HostFactory.New(x =>
    {
        x.Service<MyService>(sc =>
        {
            sc.ConstructUsing(() => new MyService());
    
            …
    
            // Handle custom commands
            sc.WhenCustomCommandReceived((service, control, command) =>
                service.CustomCommand(control, command));
        });
    });
    

    要向服务发送命令,您可以使用ServiceController.ExecuteCommand

    using (var thatService = new ServiceController("ThatService"))
    {
        thatService.ExecuteCommand(0);
    }
    

    如果您无法使用该服务的命令,您还可以使用ServiceControllerStopStart 服务:

    using (var thatService = new ServiceController("ThatService"))
    {
        thatService.Stop();
        SpinWait.SpinUntil(() =>
            {
                thatService.Refresh();
                return thatService.Status == ServiceControllerStatus.Stopped;
            });
        thatService.Start();
        SpinWait.SpinUntil(() =>
            {
                thatService.Refresh();
                return thatService.Status == ServiceControllerStatus.Running;
            });
    }
    

    或者您的恢复必须是您重新启动该服务并启动该服务的命令。

    【讨论】:

      猜你喜欢
      • 2016-07-02
      • 2014-12-08
      • 2015-10-28
      • 1970-01-01
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 2022-10-09
      相关资源
      最近更新 更多