c# - 如何捕获异常并停止 Topshelf 服务?

标签 c# topshelf

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

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

public void Start()
{
    if (!File.Exists(_xmlFile) throw new FileNotFoundException();
    // Do some work here if xml file exists.
}

但是,Windows 服务在发生异常后仍然作为一个进程存在,然后我必须在任务管理器中手动终止该异常。

有没有办法在满足某些条件(即未找到文件)时不运行该服务?

最佳答案

您可以使用 HostControl 对象并像这样修改您的方法:

public bool Start(HostControl hostControl)
{
    if (!File.Exists(_xmlFile) 
    {
        hostControl.Stop();
        return true;
    }

    // Do some work here if xml file exists.
    ...
}

并且您需要像这样将 HostControl 传递给 Start 方法:

HostFactory.Run(conf =>
{
    conf.Service<YourService>(svcConf =>
    {
        svcConf.WhenStarted((service, hostControl) =>
        {
            return service.Start(hostControl);
        }
    }
}

关于c# - 如何捕获异常并停止 Topshelf 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23791696/

相关文章:

topshelf - 如何检测 Topshelf 是否在控制台模式下运行

c# - 避免 DivideByZero 异常的好方法

c# - 需要一个模式来为每个实例方法模式调用 Verify 方法

c# - 在外部 C++ 库中检索入口点列表?

c# - Topshelf 服务(充当 TCP 服务器)与自托管 OWIN WebAPI 之间的通信

c#-4.0 - Topshelf 窗口服务在尝试启动服务时出现错误 1053

nservicebus - 在 NServiceBus 中将通用主机作为服务安装时,如何提供有效凭据?

c# - Topshelf 需要使用 Autofac 的 Quartz 作业工厂

c# - Microsoft Graph API 脚本身份验证

c# - 在不同的应用程序中复制和修改选定的文本