Enclosing service execution in try-catch: bad practice?
Below is the usual Program.cs content for a windows service program:
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);
}
}
Is it a bad practice to enclose the ServiceBase.Run(...)
in a try-catch block?
Thanks.
EDIT:
Performed some tests and found (test method: send a custom command to the service, which throws an ApplicationException in the OnCustomCommand override):
A. Enclosing ServiceBase.Run() in try/catch does not catch the exception thrown in OnCustomCommand, because the try block was already in scope when the service thread started executing. Therefore, questioning the 开发者_如何学运维corectness of this method is irrelevant as long as it doesn't fill its purpose anyway.
B. Adding a handler for AppDomain.CurrentDomain.UnhandledException did not catch the exception either.
However, in both cases the exception showed up in the Windows event log. This pretty much solves my need of knowing when something crashes during service execution but the question remains: are there any cases when a service may silently crash without any trace in the event log?
That depends on what you are doing. If you intend to treat exceptions and do something useful with them (e.g. retry, run a backup, notify the user and ask for feedback etc) then IMO I do not think this is a bad practice.
As I said, it depends on what you are doing.
精彩评论