系统相关
首页 > 系统相关> > Windows服务异常处理和计时器

Windows服务异常处理和计时器

作者:互联网

我在使用System.Timers.Timer时遇到问题.
确切地说,它不会引发任何异常.这是我的代码:

private Timer MyTimer { get; set; }

public MyService()
{
    InitializeComponent();
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    MyTimer = new Timer(10 * 1000);
    MyTimer.Elapsed += MyTimer_Elapsed;
}

protected override void OnStart(string[] args)
{
    MyTimer.Enabled = true;
}

private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    if (!EventLog.SourceExists(EVENTLOGSOURCE))
    {
        EventLog.CreateEventSource(EVENTLOGSOURCE, EVENTLOGDESCRIPTION);
    }
    EventLog.WriteEntry(EVENTLOGSOURCE, "UnhandledException\r\n" + e.ExceptionObject, EventLogEntryType.Error);
    EventLog.WriteEntry(EVENTLOGSOURCE, "UnhandledExceptionEventArgs.IsTerminating: " + e.IsTerminating, EventLogEntryType.Error);

    if (e.IsTerminating)
    {
        this.ExitCode = 100;
        //this.Stop();
    }
}

private void MyTimer_Elapsed(object sender, ElapsedEventArgs e)
{
    MyTimer.Enabled = false;
    CurrentDomain_UnhandledException(AppDomain.CurrentDomain, new UnhandledExceptionEventArgs(new Exception("FakeExceptionForTestPurposeOnly: It will be logged!"), false));

    Int32 i = Convert.ToInt32("10_ForSureGeneratesException_10");
}

因此,在我的事件日志中,我可以找到“ FakeExceptionForTestPurposeOnly:它将被记录!”但这是唯一的!

毕竟,最糟糕的部分是它仍在运行的服务.那怎么可能呢?

请注意,我已经解决了问题,在这种情况下,计时器不是强制性的. System.Threading.Thread可以达到目的,并且可以作为发条工作.我想很好奇…

因此,问题是:为什么在MyTimer_Elapsed()中发生任何UnhandledExceptions时,“ CurrentDomain_UnhandledException(object sender,UnhandledExceptionEventArgs e)”永远不会被触发?

任何帮助,建议,意见将不胜感激

解决方法:

在Windows服务中,“主”线程归服务控制管理器所有,服务控制管理器调用OnStart和OnStop方法.当其“主”线程上发生异常时,ServiceBase类负责异常处理,因此将处理该异常,并且不会将其传播到整个调用链.

尽管Windows服务中不应有SynchronizationContext,所以应该在另一个ThreadPool线程上触发Elapsed事件,但我建议您尝试使用System.Threading.Timer,并查看Elapsed事件调用回调时是否传播异常. .

标签:multithreading,exception-handling,windows-services,c,system-timers-timer
来源: https://codeday.me/bug/20191121/2051685.html