【发布时间】:2010-05-10 08:28:03
【问题描述】:
以下是 Windows 服务程序的常用 Program.cs 内容:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
}
}
将ServiceBase.Run(...) 包含在try-catch 块中是一种不好的做法吗?
谢谢。
编辑:
执行了一些测试,发现(测试方法:向服务发送自定义命令,在 OnCustomCommand 覆盖中抛出 ApplicationException):
A.在 try/catch 中包含 ServiceBase.Run() 不会捕获 OnCustomCommand 中抛出的异常,因为当服务线程开始执行时 try 块已经在作用域内。因此,只要没有达到目的,质疑这种方法的正确性是无关紧要的。
B.为 AppDomain.CurrentDomain.UnhandledException 添加处理程序也没有捕获到异常。
但是,在这两种情况下,Windows 事件日志中都出现了异常。这几乎解决了我在服务执行期间知道什么时候崩溃的需要,但问题仍然存在:是否有任何情况下服务可能会在事件日志中没有任何痕迹的情况下静默崩溃?
【问题讨论】:
标签: c# windows-services try-catch