我对 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 发生期间永远不会被触发?
任何帮助,建议,意见将不胜感激