Summary: How to write a better Windows service in Visual Studio 2008.
Last week I discovered a couple of problems related to porting my Windows service demo project from Visual Studio 2003 to Visual Studio 2008. A minor problem was caused by an obsolete method in the sample Windows service. Another problem was quite embarrassing: once started, it was impossible to stop a service from Service Control Manager. To fix this problem (and a couple of other issues related to .NET 2.0-specific functionality), I made the following changes:
- Swapped the contents of Start and OnStart methods (now the Start method calls the OnStart method).
- Moved the contents of the Stop method to the OnStop method.
- Removed the Stop method (it's really not needed).
- Modified is IsInstalled method.
- Renamed the TestService source file in the demo project to CustomService (to reflect the name of the class).
- Move your custom startup logic of a WindowService-derived class from the Start method to the OnStart method.
- Don't forget to call the base class' OnStart and OnStop methods in the corresponding overriden methods.
- Well... that's it.
Here is the Visual Studio 2008 version of the project, which incorporates all reported bug fixes up-to-date:
Write a Better Windows Service by Alek Davis