How to catch exception and stop Topshelf service?

后端 未结 6 1031
予麋鹿
予麋鹿 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:06

    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(svcConf =>
        {
            svcConf.WhenStarted((service, hostControl) =>
            {
                return service.Start(hostControl);
            }
        }
    }
    

提交回复
热议问题