在 Windows 服务中处理 AppDomain.CurrentDomain.UnhandledException

Lat*_*san 4 c# exception unhandled-exception

我有充当同步软件的窗口服务。我想在我的服务上添加无人处理的异常日志记录,所以我program.cs像这样修改了我的:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
    static void Main()
    {
        // Register Unhandled Exception Handler
        AppDomain.CurrentDomain.UnhandledException +=
            new UnhandledExceptionEventHandler(UnhandledExceptionHandler);

        // Run Service
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new Service() 
        };
        ServiceBase.Run(ServicesToRun);
    }

    static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
    {
        // Get Exception
        Exception ex = (Exception)args.ExceptionObject;

        // Generate Error
        string ErrorMessage = String.Format(
            "Error: {0}\r\n" +
            "Runtime Terminating: {1}\r\n----- ----- ----- ----- ----- -----\r\n\r\n" +
            "{2}\r\n\r\n####################################\r\n",
                ex.Message,
                args.IsTerminating,
                ex.StackTrace.Trim());

        // Write Error To File
        try
        {
            using (StreamWriter sw = File.AppendText("UnhandledExceptions.log"))
                sw.WriteLine(errorMessage);
        }
        catch { }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的Service.cs文件的OnStart方法中,我添加了一个throw new Exception("test");来查看未处理的异常是否按预期记录到文件中。

当我启动服务时,它会按预期立即停止;但是它似乎没有将异常记录到指定的文件中。

知道我在这里做错了什么吗?预先感谢您的任何帮助。

在您询问之前,我的服务运行时,Local Service我的服务 .exe 运行所在的目录 (c:\mysync) 已Local Service添加到具有完全读/写访问权限的安全选项卡中。

Igo*_*nko 5

OnStart 在 try-catch 块内的 Service 基类中调用。如果此阶段发生异常,它会捕获该异常并仅将状态设置为 1,并且不会进一步抛出异常:

  string[] args = (string[]) state;
  try
  {
    this.OnStart(args);
    .....
  }
  catch (Exception ex)
  {
    this.WriteEventLogEntry(Res.GetString("StartFailed", new object[1]
    {
      (object) ((object) ex).ToString()
    }), EventLogEntryType.Error);
    this.status.currentState = 1;
  }
Run Code Online (Sandbox Code Playgroud)

因此,您可以在 EventLogs 中找到一条记录,但无法将其捕获为未处理的域异常,因为不存在此类异常。