How to catch exception and stop Topshelf service?

后端 未结 6 1029
予麋鹿
予麋鹿 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 03:50

    When you catch the exception you can use ServiceBase.Stop() Method to stop the service by itself.

    try
    {
        // Your Code
    }
    catch (Exception ex)
    {
        // The code for stopping service
    }
    

    Also you can have multi catch blocks in some cases:

    try
    {
        // Your Code
    }
    catch (IndexOutOfRengeException ex)
    {
        // The code for stopping service
    }
    catch (FileNotFoundException exc)
    {
        // The code for stopping service
    }
    

    Read more about ServiceBase.Stop()

提交回复
热议问题