我有一个 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/