Closing a service 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 bad practice ServiceBase.Run(...)

to wrap a try-catch block?

Thanks.


EDIT:

Several tests run and found (test method: send custom command to service that throws ApplicationException in OnCustomCommand override):

and. 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, the question of whether this method is inappropriate is irrelevant if it still fails its purpose.

C. Adding a handler for AppDomain.CurrentDomain.UnhandledException also did not throw an exception.

However, in both cases, an exception appeared in the Windows event log. This pretty much solves my need to know when something crashes during the execution of a service, but the question remains: are there cases where a service can silently crash without any trace in the event log?

+2


a source to share


1 answer


It depends on what you are doing. If you intend to handle exceptions and do something useful with them (like retrying, running a backup, notifying the user and asking for feedback, etc.), then IMO I don't think this is bad practice.



As I said, it depends on what you are doing.

+2


a source







All Articles