首页 > 解决方案 > topshelf windows服务失败后没有重启

问题描述

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

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

标签: windows-servicestopshelf

解决方案


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

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

推荐阅读