gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:56:20 25 4
gpt4 key购买 nike

我有充当同步软件的窗口服务。我想在我的服务上添加未处理的异常日志记录,所以我修改了我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com