[英]Catching unhandled exception Windows Service
我寫了一個像這樣的窗口服務:
public partial class Service1 : ServiceBase
{
private Thread writerThread;
private Thread messageThread;
private bool stopNow;
public Service1()
{
}
private void MessageThread()
{
while (stopNow == false)
{
try
{
//Do Something
Thread.Sleep(10000);
}
catch (Exception e)
{
GLogWriter.Write(String.Format("Critical exception {0}. Inner Exception {1} ", e.Message, e.InnerException.Message), LogCategories.Generic, TraceEventType.Critical);
OnStop();
}
}
}
private void WriterThread()
{
bool checkGruppoIndirizzi = true;
while (stopNow == false)
{
try
{
//Do something else
Thread.Sleep(10000);
}
catch (Exception e)
{
GLogWriter.Write(String.Format("Critical exception {0}. Inner Exception {1} ", e.Message, e.InnerException.Message), LogCategories.Generic, TraceEventType.Critical);
OnStop();
}
}
}
protected override void OnStart(string[] args)
{
GLogWriter.Write("SERVICE IS STARTING", LogCategories.Generic, TraceEventType.Information);
this.stopNow = false;
writerThread = new Thread(new ThreadStart(this.WriterThread));
writerThread.Start();
this.messageThread = new Thread(new ThreadStart(this.MessageThread));
this.messageThread.Start();
}
protected override void OnStop()
{
GLogWriter.Write("SERVICE IS STOPPING", LogCategories.Generic, TraceEventType.Information);
stopNow = true;
writerThread.Join(1000);
messageThread.Join(1000);
GLogWriter.Write("SERVICE STOP SUCCESSFUL", LogCategories.Generic, TraceEventType.Information);
}
}
}
問題是當我抓住一個異常顯然沒有調用OnStop()並且服務立即停止而沒有記錄“SERVICE IS STOPPING”消息
請查看Windows事件日志以查看您獲得的錯誤或異常類型。 如果它是一個程序異常,它肯定會被catch捕獲。 所以我懷疑服務在系統級別拋出異常。
這應該通過事件日志來診斷。
當服務的線程停止工作時, OnStop()
方法不應被調用。 這是一個特殊的過程,應該由服務控制管理器調用。 換句話說, OnStop()
是應該在需要時正常停止服務的過程。 東西調用OnStop()
- >服務停止。 它不是相反(在服務中發生的事情 - >線程退出 - > OnStop()
被調用)
這是因為以下行:
GLogWriter.Write(String.Format("Critical exception {0}. Inner Exception {1} ", e.Message, e.InnerException.Message), LogCategories.Generic, TraceEventType.Critical);
InnerException
並不總是一個對象,而是通常為null
。
將該行更改為:
GLogWriter.Write(String.Format("Critical exception {0}. Inner Exception {1} ", e.Message, ((e.InnerException == null) ? string.Empty : e.InnerException.Message)), LogCategories.Generic, TraceEventType.Critical);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.