I have a TopShelf (3.1.3) service that hangs in a 'Stopping' state when an exception is raised. As a result none of the service recovery steps get invoked, and uninstalling the service only succeeds if the service is manually killed via 'taskkill'.
What is the recommended approach for handling exceptions in TopShelf? I do not wish to simply swallow/log the exception and continue. Ideally the call to hostControl.Stop would indeed put the service in a 'stopped' state, however this is not the case.
This thread asks a similar question, however it does not provide an answer: How to catch exception and stop Topshelf service?
Thoughts?
HostFactory.Run(o =>
{
o.UseNLog();
o.Service<TaskRunner>();
o.RunAsLocalSystem();
o.SetServiceName("MyService");
o.SetDisplayName("MyService");
o.SetDescription("MyService");
o.EnableServiceRecovery(r => r.RunProgram(1, "notepad.exe"));
});
public class TaskRunner : ServiceControl
{
private CancellationTokenSource cancellationTokenSource;
private Task mainTask;
public bool Start(HostControl hostControl)
{
var cancellationToken = cancellationTokenSource.Token;
this.mainTask = Task.Factory.StartNew(() =>
{
try
{
while (!this.cancellationTokenSource.IsCancellationRequested)
{
// ... service logic ...
throw new Exception("oops!");
}
}
catch (Exception)
{
hostControl.Stop();
}
});
return true;
}
public bool Stop(HostControl control)
{
this.cancellationTokenSource.Cancel();
this.mainTask.Wait();
return true;
}
}