topshelf windows 服务失败后未重新启动

topshelf windows service is not restarted after failure

我已经使用 Topshelf 创建了一个 Windows 服务,这是我的配置:

HostFactory.Run(serviceConfig =>
{
    serviceConfig.Service<ServiceScheduler>(serviceInstance =>
    {
        serviceInstance.ConstructUsing(() => new ServiceScheduler());
        serviceInstance.WhenStarted((execute, hostControl) => execute.Start(hostControl));
    });

    serviceConfig.EnableServiceRecovery(recoveryOption =>
    {
        /* recoveryOption.OnCrashOnly();    // restart the service only after crash */
        recoveryOption.RestartService(1);   // first failure
        recoveryOption.RestartService(5);   // second failure
        recoveryOption.RestartService(5);   // third failure
    });
}
serviceConfig.StartAutomatically();

请注意,我没有使用:recoveryOption.OnCrashOnly()

我的服务是基于计时器的服务,每 30 秒调用一次以下事件处理程序。

// this event handler is called every 30 seconds
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
    try
    {
        // I throw an exception from inside this method
        _syncer.DoSync();
    }
    catch (Exception ex)
    {
        LogConfig.Logger.Fatal(ex);
        _hostControl.Stop(); 
    }
}

这会停止服务,但服务不会在 1 分钟后重新启动。不确定为什么?

注意:安装服务后我没有重启电脑,不知道是否需要重启?

我发现我的错误,我不得不用非零退出代码停止服务:

// this event handler is called every 30 seconds
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
    try
    {
        // exception is thrown from inside this function
        _syncer.DoSync();
    }
    catch (Exception ex)
    {
        LogConfig.Logger.Fatal(ex);
        // kill the service with a non-zero exit code, so it would be restarted
        _hostControl.Stop(TopshelfExitCode.UnhandledServiceException);  
    }
}