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?
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);
}
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With