失败后不会重新启动topshelf Windows服务

时间:2018-06-21 02:04:29

标签: windows-services topshelf

我已经使用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分钟后不会重新启动。不知道为什么吗?

注意:安装该服务后,我还没有重新启动PC,不确定是否需要这样做?

1 个答案:

答案 0 :(得分: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);  
    }
}