[英]Windows Service Exception Handling and Timers
我有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(對象發送者,UnhandledExceptionEventArgs e)”永遠不會被觸發?
任何幫助,建議,評論將不勝感激
在Windows服務中,“主”線程由Service Control Manager
擁有, Service Control Manager
調用OnStart
和OnStop
方法。 當其“Main”線程發生異常時, ServiceBase
類負責異常處理,從而處理異常並且不會將其傳播到調用鏈中。
雖然Windows服務中應該沒有SynchronizationContext
,因此應該在不同的ThreadPool
線程上觸發Elapsed
事件,我建議您嘗試使用System.Threading.Timer
,並查看當Elapsed
事件調用您的回調時異常是否傳播。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.