抛出异常时重新启动服务

时间:2009-07-29 16:29:43

标签: vb.net windows-services

我正在编写一个需要全天候运行的Windows服务。这是一个非常简单的服务,它监视文件被放入的目录并处理这些文件。如果抛出未处理的异常,我需要重启服务。

如果出现未处理的异常,服务是否有办法重新启动?

6 个答案:

答案 0 :(得分:2)

您是否尝试使用服务条目的恢复选项卡 - 您可以设置失败规则,包括“重新启动服务” - 默认情况下这是“无操作”

答案 1 :(得分:2)

服务小程序具有许多不同的恢复功能:

Services Recovery

对第一次,第二次和随后的失败采取不同的行动:

  • 在可配置的延迟后重启服务
  • 运行程序(传递命令行参数,可能包括失败计数)
  • 重新启动计算机(在可配置的延迟之后,并发送特定消息)

运行的程序应该能够查看事件日志并查看失败的原因(特别是如果您记录它),因此如果异常是不可恢复的,则应该能够禁用该服务。 / p>

当然,与此同时,服务应该记录正在发生的事情,这应该使任何管理工具能够通知操作正在发生的事情。

我同意你可能不应该将“第三次和后续”配置为“重启服务”,否则你可能会陷入困境。

答案 2 :(得分:1)

如果您愿意,可以以编程方式完成,此代码不是由我编写的。我发布了包含源/二进制文件的Authors CodeProject页面的链接。在链接下面,我已经解释了我是如何实现作者代码的。

http://www.codeproject.com/KB/install/sercviceinstallerext.aspx

  1. 添加对DLL的引用。

  2. 在记事本中打开ProjectInstaller.Designer.vb
    在InitializeComponent Sub中 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

  3. 使用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

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

  5. 在ProjectInstaller.vb上导入命名空间

  6. PublicInstaller.vb中的Public Sub新函数初始化组件函数被调用后
     ADD
      '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

  7. 构建安装程序并安装。 Voila

答案 3 :(得分:0)

将您的服务代码包含在可以捕获任何错误并重新启动服务的跑步者中。

答案 4 :(得分:0)

最好的方法是围绕您可以承担的服务中的方法包装Try / Catch块以抛出异常。

但是,可能会出现严重的异常,导致服务立即停止。不要忽视这些!在这些情况下,处理异常,记录它,通过电子邮件发送它然后重新抛出它。这样,您将被告知异常已经发生,并将知道出了什么问题。然后,您可以解决问题并手动重新启动服务。

忽略它可能会导致您的系统出现重大故障,而您却不知道。如果服务停止然后重新启动然后停止 ad infinitum ,它在CPU / RAM上也可能非常昂贵。

答案 5 :(得分:0)

根据“John Saunders”和“theGecko”的建议,您可以监控服务并在失败时重新启动它。内置的Windows服务恢复功能将为您提供很长的路要走,但如果您发现需要一些更高级的功能(例如,CPU占用和挂起检测),请查看Service Protector。它旨在让您的重要Windows服务全天候运行。

祝你好运!

相关问题