How to catch exception and stop Topshelf service?

后端 未结 6 1008
予麋鹿
予麋鹿 2020-12-31 03:22

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

6条回答
  •  被撕碎了的回忆
    2020-12-31 04:07

    I just ran into this issue and all the above answers seem to be over complicating things. All you need to do is use the WhenStarted overload that accepts a Func and return false if your internal service bootstrap failed. I don't think hostControl.Stop() needs to be called explicitly.

    //Here is bit from inside the .Service() call
    s.WhenStarted((YourService svc, HostControl hc) => svc.Start());
    
    //And the svc.Start method would look something like this:
    class YourService
    {
       public bool Start() {
         //return true if all is well
         //or false if you want service startup to be halted
       }
    }
    

提交回复
热议问题