C# Windows服务异常处理和计时器
我对System.Timers.Timer有问题。 确切地说,它不会抛出任何异常。这是我的密码:C# Windows服务异常处理和计时器,c#,multithreading,exception-handling,windows-services,system.timers.timer,C#,Multithreading,Exception Handling,Windows Services,System.timers.timer,我对System.Timers.Timer有问题。 确切地说,它不会抛出任何异常。这是我的密码: private Timer MyTimer { get; set; } public MyService() { InitializeComponent(); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; MyTimer = new Timer(10 * 100
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_Appeased()中发生任何未处理的异常时,“CurrentDomain_UnhandledException(对象发送方,UnhandledExceptionEventTarget)”永远不会被触发?
任何帮助、建议和评论都将受到欢迎在Windows服务中,“主”线程由服务控制管理器
拥有,该管理器调用OnStart
和OnStop
方法。当异常发生在其“主”线程上时,ServiceBase
类负责异常处理,因此负责处理异常,不会将其传播到调用链上
虽然Windows服务中不应该有
SynchronizationContext
,因此应该在不同的ThreadPool
线程上触发appeased
事件,但我建议您改为尝试System.Threading.Timer
,并查看当事件调用回调时异常是否传播。this.Stop();是评论??!!是的,是:-)但这没关系。出现“this.Stop();”的原因仅仅是为了防止在调试期间自动重新启动服务(导致windows在出现错误停止时处理服务的重新启动)。问题是“MyTimer不会触发未经处理的异常”,你能再补充一点解释吗?你说你对什么好奇,但我不知道你对什么好奇。你预期会发生什么,发生了什么/没有发生什么与你的预期不符?@Damien_The_The_unsiver在我上一次编辑时,我刚刚添加了我所关注的内容。你是对的,问题在于同步上下文。