I hope you know that the services can be started automatically on system start-up, this is one of the standard options of the service installation which can be changed at any time using the Service Controller or services applet:
%windir%\system32\services.msc
So, if the host running the service is rebooted, the service will restart automatically.
What to do with other problems disrupting the service? I agree with you: the idea of regular restarting of a service from time to time would not work properly.
Well, you will
really need to make your service fail-tolerant. Use the following principles:
Execute every logically distinct activity in a separate thread. Make sure you are not working with random or unpredictable number of threads. The best approach is creating a fixed number of threads in the very beginning and keeping them either working or in a wait state, waiting at some blocking call (like in case of networking) or a call to thread synchronization primitives. Is such state, the thread consumes zero CPU time until waken up by some thread synchronization event.
Catch all exceptions at the very top of each thread by wrapping it in the try-catch-finally block. Besides, devise an "infinite" outer execution loop where you can use a last chance to catch any exception and try to restart. Schematically, it should look like this:
void ServiceThreadBody() {
while(!exitCondition) {
try {
MainThreadCycle();
} catch (MySpecificException e) {
ProcessSpecificException(e);
} catch (MyOtherSpecificException e) {
ProcessAnotherSpecificException(e);
} catch {
ProcessUnexpectedException();
} finally {
SomeUniversalCleanUp();
}
}
}
void MainServiceCycle() {
while (keepServicingCondition) {}
}
When you handle an exception, you need to perform necessary clean up. One thing you would need to do is to log the exception information to the system log using the class
System.Diagnostics.EventLog
, please see:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx[
^].
Do something like that in each thread performing the service.
For some particular idea on fault tolerance, on the example of network service, please see my past answer:
Multple clients from same port Number[
^].
Please see my past answers on advanced use of logging:
How to create event log under a folder[
^],
MsBuild OutPut to the TextBox on the fly in Windows Application[
^].
Please see my past answers on some ideas on exception handling:
When i run an application an exception is caught how to handle this?[
^],
throw . .then ... rethrowing[
^],
Handling exceptions in class library (dll)[
^].
—SA