c# - 在 Windows 服务中处理 AppDomain.CurrentDomain.UnhandledException

标签 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 { }
    }
}

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

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

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

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

最佳答案

OnStart 在 try-catch block 内的服务基类中调用。如果在此阶段发生异常,它会捕获它并将状态设置为 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;
  }

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

关于c# - 在 Windows 服务中处理 AppDomain.CurrentDomain.UnhandledException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23114479/

相关文章:

c# - 如何计算字符串中的行数?

c# - 如何反序列化具有包含不同对象的属性的 json?

python - 如何通过 try/except 正确处理 KeyError 异常?

java - 捕获错误(而不是异常)有什么意义,因为程序不会由 JVM 启动

c - 动态分配的二维数组

c# - MMC 管理单元和 .Net 4.x

exception - 同时以错误级别记录每个异常

c# - NullReferenceException 未处理 - 不确定什么是 null

c# - 播放数组中的声音会返回错误C#-Visual Studio

c# - .NET 框架 : Get Type from TypeInfo