Friday, June 1, 2012

Self restarting windows services

I recently went through an interview where the interview was running over and the interviewer was trying to kill time so he was telling me about a GDI+ handle bug in .NET. Now for those who know me and have read my published works, you know that I am a UI specialist, so my ears instantly perked up to listen to this issue.

The situation was that they were using a windows service that was creating images and printing them off or something. Anyhow since the service wasn’t a GUI app it was not constantly being started and stopped and so with time it would use up all the available handles.

The solution that this person came up with was to create another service to watch the handles in the other service and when it had to many it would start another service to restart the first service.

To clarify:

Service A creates and prints images that use up handles in GDI+

Service B watches Service A for high handle usage, on detection it starts Service C

Service C restarts Service A

Wow that’s a lot of code and work. How I would deal with it is a combination of configuration and code all in Service A.

So we have Service A keep track of the handle counts, then when we hit the thresh hold we have the service call Environment.Exit with an error code greater than 0, which seems appropriate. Then on install we configure the service to restart on error.

Voila a self restarting service, well sort of, but much less complex than the previous scenario.