3

我对 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() "CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)" 中的任何 UnhandledExceptions 发生期间永远不会被触发?

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

4

1 回答 1

3

在 Windows 服务中,“主”线程由Service Control Manager调用OnStartOnStop方法的 拥有。当其“主”线程上发生异常时,ServiceBase该类负责异常处理,因此会处理异常并且不会将其传播到调用链上。

尽管SynchronizationContextWindows 服务内部不应该有,因此Elapsed应该在不同的ThreadPool线程上触发事件,但我建议您尝试System.Threading.Timer改用,看看当Elapsed事件调用您的回调时异常是否传播。

于 2014-08-01T07:29:01.247 回答