How to catch exception and stop Topshelf service?

JD. picture JD. · May 21, 2014 · Viewed 18.3k times · Source

I have a topshelf windows service where I want to do some checking (i.e. if an xml file exists) and if the check fails I need the windows service to stop.

So I tried doing the check in the Start() method and then raise an exception:

public void Start()
{
    if (!File.Exists(_xmlFile) throw new FileNotFoundException();
    // Do some work here if xml file exists.
}

However, the windows service stays around as a process after the exception which I then have to kill manually in the task manager.

Is there a way to not run the service if certain conditions (i.e. file not found) hold?

Answer

julio.g picture julio.g · Jan 30, 2015

You could use the HostControl object and modify your method like this:

public bool Start(HostControl hostControl)
{
    if (!File.Exists(_xmlFile) 
    {
        hostControl.Stop();
        return true;
    }

    // Do some work here if xml file exists.
    ...
}

And you will need to pass the HostControl in to the Start method like this:

HostFactory.Run(conf =>
{
    conf.Service<YourService>(svcConf =>
    {
        svcConf.WhenStarted((service, hostControl) =>
        {
            return service.Start(hostControl);
        }
    }
}