Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch exception and stop Topshelf service?

Tags:

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?

like image 278
JD. Avatar asked May 21 '14 19:05

JD.


2 Answers

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);
        }
    }
}
like image 86
julio.g Avatar answered Nov 01 '22 08:11

julio.g


Each of the WhenXxx methods can also take an argument of the HostControl interface, which can be used to request the service be stopped, request additional start/stop time, etc.

In such case, change signature of start() to be bool start(HostControl hc). Retain reference to this HostControl in the service as follow:

public bool Start(HostControl hc)
{
    hostControl = hc;
    Restart();
    return true;
}

Now when you want to stop the service use following call:

hostControl.Stop();
like image 22
101V Avatar answered Nov 01 '22 08:11

101V