gpt4 book ai didi

c# - 未处理 Windows 服务异常

转载 作者:行者123 更新时间:2023-11-30 18:06:30 27 4
gpt4 key购买 nike

我有基于类 ServiceBase 的常规 C# 服务。该服务在启动时加载 C++ 动态链接库。有时会发生非托管代码中的服务崩溃。不幸的是,事件查看器只给出了非常简短的描述。如果他的消息是这样的:

Application: StreamMapService.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: exception code c0000005, exception address 00000012".

有 99% 的把握问题出在非托管代码中。问题是这种情况很少发生(通常一天一次)并且仅在作为服务运行时发生。在调试器下一切正常。为了找出有问题的代码,我按以下方式编辑了我的主要方法:

    static void Main()
{
try
{
if (!Environment.UserInteractive)
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
else
{
var services = new Service1();
services.Start();
Console.WriteLine("Press return to exit");
Console.ReadLine();
services.Stop();
}
}
catch (SEHException e)
{
// wrapper for all exceptions having its origin in unmanaged code
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Crash time: {0}\n", DateTime.Now.ToString());
sb.AppendFormat("\nMessage:\n{0}", e.Message);
sb.AppendFormat("\nSource: {0}\n", e.Source);
sb.AppendFormat("Stack trace:\n{0}", e.StackTrace);
sb.AppendFormat("\nTarget site:{0}", e.TargetSite);

SmtpClient client = new SmtpClient("mail.domain.com");
MailAddress from = new MailAddress("sender@domain.com", "sender", System.Text.Encoding.UTF8);
MailAddress to = new MailAddress("receiver@domain.com");
MailMessage message = new MailMessage(from, to);
message.Body = sb.ToString();
message.Subject = "StreamMapService crash info";
client.Send(message);
throw;
}
}

为了测试这个异常处理程序,我在非托管代码的某些部分生成了测试异常。当我在调试器或命令行下运行服务时,一切正常。

我收到包含异常信息的电子邮件(最重要的是它包含非托管异常产生的调用堆栈)。

但是当我将此程序作为系统服务运行时(从控制面板 -> 管理工具 -> 服务),服务明显崩溃(它在 tcp 接口(interface)上变得无响应,并且事件查看器包含崩溃信息)但我没有收到任何电子邮件。

看起来在这种情况下甚至没有调用异常处理程序。我试图将异常信息写入文件,但同样发生了。

因此,当在调试器或命令行下运行时,调用堆栈信息会被正确记录。当作为系统服务运行时,什么也没有发生。在这种情况下,异常处理似乎无法正常运行。

最佳答案

异常可能是在另一个线程上抛出的。尝试在您的代码之前添加以下内容以捕获任何未处理的异常:

AppDomain.CurrentDomain.UnhandledException += 
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

事件处理程序应具有以下签名:

void CurrentDomain_UnhandledException(
object sender, UnhandledExceptionEventArgs e) {
}

关于c# - 未处理 Windows 服务异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4791303/

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