Search code examples
servicewindows-servicesbackgroundworkerbackground-service

Design and Error handling in windows service


I have to design windows service and I have some question:

  1. Proper error handling, if there is an error what happens to the service? Does he continue to be up and logging in? Error recording in event viewer? Is he falling?
  2. What happens to a long run? How do you know for sure that everything is running as required, and he is not stuck?
  3. How to handle high memory consumption, out of memory, or other error that wasn't been write to the log?
  4. Handle users - what happened if create log to user A and changed to user B? Rewrite or continue from same point?
  5. How to handle times? - Is the service automatically up?

Thank you.


Solution

    1. For error handling, the best I can recommend is taking advantage of try / catch cases. This way you ensure that you handle the cases where something unexpected happens and you can either try to correct it or bring the service down cleanly. Keep in mind that exceptions are not propagated outside the scope of a thread so you need to handle them in each thread.

    2. To be able to tell if the service is doing fine, you can periodically log into the Event Log what the service does. If you do proper try / catch for each thread, it should go smoothly. In C# you can use log4net and the EventLogAppender to log crucial / error info in the Event Log.

    3. If your service causes high memory usage for no apparent reason, it is likely a memory leak. Microsoft has a free tool called ".Net CLR profiler" that allows you to properly profile your service and see what exactly is causing the leak.

    4. Unless you are dealing with user-protected files (in which case you need to consult the Log On tab of your service to give it the appropriate credentials), your service shouldn't depend on any logged-in user. Services run independently of the users on the computer.

    5. A service can be set to start automatically, to start only on-demand, or to simply be disabled completely.