我在写一个需要全天候运行的Windows服务。这是一个非常简单的服务,它监视文件被放入并处理这些文件的目录。如果抛出未处理的异常,我需要重新启动服务。当抛出异常时重新启动服务
有没有办法使服务在发生未处理的异常时自行重启?
我在写一个需要全天候运行的Windows服务。这是一个非常简单的服务,它监视文件被放入并处理这些文件的目录。如果抛出未处理的异常,我需要重新启动服务。当抛出异常时重新启动服务
有没有办法使服务在发生未处理的异常时自行重启?
服务小程序有许多不同的恢复特性:
它可以在第一,第二和随后的故障不同的操作:
运行应该能看在事件日志中看到失败(特别是如果你登录的话)的原因,程序,因此如果该异常是不可恢复的异常,则应该能够禁用该服务。
而且,当然,在此期间,服务应记录正在发生的事情,这应该使任何管理工具能够通知操作人员发生了什么。
我同意你可能不应该配置“第三个和后续”为“重新启动服务”,或者你可以结束循环。
您是否尝试过使用服务项的恢复选项卡 - 可以设置故障规则,包括“重新启动服务” - 默认情况下,这是对“不采取行动”
在亚军包装你的服务代码它可以捕获任何错误并重新启动服务。
最好的方法是围绕服务中的方法包装Try/Catch块,您可以通过负责来引发异常。
但是,可能会引发严重的异常,导致服务立即停止。不要忽视这些!在这些情况下,处理异常,记录它,发送电子邮件然后重新抛出它。这样你会被告知异常已经发生,并且会知道出了什么问题。然后,您可以修复问题并手动重新启动该服务。
只是忽略它可能会导致您的系统出现重大故障,您不知道。如果服务停止然后重启然后停止无限,它也可能在CPU/RAM上非常昂贵。
这是可以通过编程方式完成,如果你想,这段代码不是由我写的。我将链接发布到包含源代码/二进制文件的作者CodeProject页面。在链接下面,我已经解释了我是如何实现作者代码的。
http://www.codeproject.com/KB/install/sercviceinstallerext.aspx
添加到DLL的引用。
打开ProjectInstaller.Designer.vb在记事本
在InitializeComponent子
CHANGE
Me.ServiceProcessInstaller1 = New System.ServiceProcess.ServiceProcessInstaller
Me.ServiceInstaller1 = New System.ServiceProcess.ServiceInstaller
TO
Me.ServiceProcessInstaller1 = New System.ServiceProcess.ServiceProcessInstaller
Me.ServiceInstaller1 = New Verifide.ServiceUtils.ServiceInstallerEx
随着朋友声明在ProjectInstaller。 Designer.vb
CHANGE
Friend WithEvents ServiceProcessInstaller1 As System.ServiceProcess.ServiceProcessInstaller
Friend WithEvents ServiceInstaller1 As System.ServiceProcess.ServiceInstaller
TO
Friend WithEvents ServiceProcessInstaller1 As System.ServiceProcess.ServiceProcessInstaller
Friend WithEvents ServiceInstaller1 As Verifide.ServiceUtils.ServiceInstallerEx
CHANGE
Me.Installers.AddRange(New System.Configuration.Install.Installer() {Me.ServiceProcessInstaller1, Me.ServiceInstaller1})
TO
Me.Installers.AddRange(New System.Configuration.Install.Installer() {Me.ServiceInstaller1, Me.ServiceProcessInstaller1})
导入命名空间在ProjectInstaller.vb
在ProjectInstaller.vb在公用Sub新功能初始化组件函数被调用
之后添加
'Set Reset Time Count - This Is 4 Days Before Count Is Reset
ServiceInstaller1.FailCountResetTime = 60 * 60 * 24 * 4
'ServiceInstaller1.FailRebootMsg = "Houston! We have a problem"
'Add Failure Actions
ServiceInstaller1.FailureActions.Add(New FailureAction(RecoverAction.Restart, 60000))
ServiceInstaller1.FailureActions.Add(New FailureAction(RecoverAction.Restart, 60000))
ServiceInstaller1.FailureActions.Add(New FailureAction(RecoverAction.None, 3000))
ServiceInstaller1.StartOnInstall = True
编译安装程序并安装。 Voila
正如“John Saunders”和“thegecko”所建议的那样,您可以监视服务并在服务失败时重新启动服务。内置的Windows服务恢复功能将为您带来很长的路要走,但是如果您发现需要更高级的功能(例如CPU占用和挂起检测),那么请查看Service Protector。它旨在让您的重要Windows服务全天候运行。
祝你好运!
我没有意识到,这是甚至可用。谢谢! – 2009-07-29 16:37:03