Hooman Bahreini
Hooman Bahreini

Reputation: 15559

topshelf windows service is not restarted after failure

I have created a Windows Service using Topshelf, this is my configuration:

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();

Note that I am not using: recoveryOption.OnCrashOnly()

My Service is a Timer based service and the following event handler is called every 30 seconds.

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

This stops the service, but the service does not restart after 1 min. Not sure why?

Note: I have not rebooted the PC after installing the service, not sure if that's needed?

Upvotes: 0

Views: 1415

Answers (1)

Hooman Bahreini
Hooman Bahreini

Reputation: 15559

I found my mistake, I had to stop the service with a non-zero exit code:

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

Upvotes: 2

Related Questions