如何捕获异常并停止Topshelf服务? [英] How to catch exception and stop Topshelf service?

查看:65
本文介绍了如何捕获异常并停止Topshelf服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个topshelf Windows服务,我想在其中进行一些检查(即是否存在xml文件),如果检查失败,我需要Windows服务停止.

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.

所以我尝试在Start()方法中进行检查,然后引发异常:

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.
}

但是,在发生异常之后,Windows服务仍然作为一个进程存在,然后我必须在任务管理器中手动将其杀死.

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?

推荐答案

我已经借用"了topshelf功能设置的示例代码来说明这一点:

I've "borrowed" the sample code for the functional setup of topshelf to demonstrate a point:

HostFactory.Run(x =>                                 //1
    {
        x.Service<TownCrier>(s =>                        //2
        {
           s.ConstructUsing(name=> new TownCrier());     //3
           s.WhenStarted(tc => tc.Start());              //4
           s.WhenStopped(tc => tc.Stop());               //5
        });
        x.RunAsLocalSystem();                            //6

        x.SetDescription("Sample Topshelf Host");        //7
        x.SetDisplayName("Stuff");                       //8
        x.SetServiceName("stuff");                       //9
    });    

在上面的代码运行之前,您将必须对文件系统进行检查.让我们再考虑一下.提供服务的目的是确保其运行并保持运行状态.您试图颠覆首先拥有服务应用程序的基本原理.找出因缺少文件而试图停止服务的方法,而不是想出一种方法来提醒您的支持人员,而不要根据丢失的文件来做任何事情.

You're going to have to place your file system check BEFORE the above code runs. Let's think about this a second. The point of having a service is to make sure it RUNS and KEEPS RUNNING. You're attempting to subvert a basic principle of having service applications in the first place. Instead of trying to stop the service because of the missing file, figure out some way to alert your support staff and NOT do whatever depends on that missing file.

这篇关于如何捕获异常并停止Topshelf服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆