Hi,
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?