我写了这样一个窗口服务:
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”消息的情况下立即停止
答案 0 :(得分:1)
请查看Windows事件日志以查看您获得的错误或异常类型。如果它是一个程序异常,它肯定会被catch捕获。所以我怀疑服务在系统级别抛出异常。
应该通过事件日志来诊断。
答案 1 :(得分:1)
OnStop()
方法不应被调用。这是一个特殊的过程,应该由服务控制管理器调用。换句话说,OnStop()
是应该在需要时正常停止服务的过程。有人打电话OnStop()
- >服务已停止。它不是相反的(服务中发生的事情 - >线程退出 - > OnStop()
被调用)
答案 2 :(得分:0)
这是因为以下一行:
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);