【发布时间】:2014-09-24 07:33:51
【问题描述】:
我对 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 发生期间永远不会被触发?
任何帮助、建议、cmets 将不胜感激
【问题讨论】:
-
this.Stop();被评论了??!!
-
是的 :-) 但没关系。 “this.Stop();”存在的原因它只是为了防止在调试期间自动重启服务(因为当出现错误停止时,Windows 会处理服务的重启)。问题是“MyTimer 不会触发 UnhandledException”
-
你能补充一点解释吗?你说你对某事感到好奇,但我不知道你对什么感到好奇。您预计会发生什么,发生了什么/没有发生什么与您的期望不符?
-
@Damien_The_Unbeliever 在我上次编辑期间,我刚刚添加了我感兴趣的内容。
标签: c# multithreading exception-handling windows-services system.timers.timer