代码之家  ›  专栏  ›  技术社区  ›  pc1oad1etter

如何检测直接进入停止状态而没有错误的.net服务的问题

  •  2
  • pc1oad1etter  · 技术社区  · 16 年前

    我有一个.Net服务开始拒绝启动-系统日志显示它“已成功发送启动控制”,五秒钟后“服务进入停止状态”。我将我的服务类的Main()函数包装在一个try/catch块中——但是当这种情况发生时,我的服务的事件日志中不会出现错误。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    
    namespace MyServerService
    {
        static class service
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            static void Main()
            {
                try
                    {
    #if DEBUG
    
                        System.Diagnostics.Debugger.Launch();
    
    #endif
    
                        ServiceBase[] ServicesToRun;
                        ServicesToRun = new ServiceBase[] 
                    { 
                        new MyService() 
                    };
                        ServiceBase.Run(ServicesToRun);
                } catch (Exception ex)
                {
                    System.Diagnostics.EventLog.WriteEntry("MyServerService", "Main() Error: " + ex.Message + ex.InnerException, System.Diagnostics.EventLogEntryType.Error);
                }
            }
        }
    }
    
    5 回复  |  直到 16 年前
        1
  •  1
  •   casperOne    16 年前

    Run方法不会在这里抛出。相反,您需要将MyService类上OnStart方法的重载中的代码包装在try/catch块中,因为这就是发生异常的地方。

        2
  •  1
  •   Stu Mackellar    16 年前

    你的工作是什么 ServiceBase.OnStart

        3
  •  1
  •   pc1oad1etter    16 年前

    在这种情况下,我正在将日志写入Windows应用程序日志——在生产环境中,日志已满。我不确定调试技术应该是什么来“捕捉”这类问题,但这是我们的问题。

        4
  •  0
  •   Bravax    16 年前

    我会检查服务所依赖的所有组件是否安装正确。

        5
  •  0
  •   Matthew Brubaker    16 年前

    您可以向AppDomain.Current.UnhandledException添加处理程序,并将一些日志代码放入异常处理程序。这将允许您捕获导致服务停止的任何异常。

    在VB.NET中,它看起来像这样

    Sub Main(ByVal ParamArray parameters As String())
        AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf AppDomainExceptionHandler
    
    ...
    
    End Sub
    
    Private Sub AppDomainExceptionHandler(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
    
    ...
    
    End Sub