Monday, February 23, 2009

Implementing Windows services in Visual Studio 2008

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).
If you have been using the My.Utilities library to implement a Windows service and are planning to upgrade it to the Visual Studio 2008 version, please use the updated projects (see the download link below) and keep an eye on the following:
  1. Move your custom startup logic of a WindowService-derived class from the Start method to the OnStart method.
  2. Don't forget to call the base class' OnStart and OnStop methods in the corresponding overriden methods.
  3. Well... that's it.
One other thing that I could've done would be using the nullable DateTime members and variables when checking for uninitialized date and time values (instead of DateTime.MinValue), but since this would not improve functionality, I left the current implementation as is. If you strive for code elegance, feel free to do it yourself, since you have the source.

Here is the Visual Studio 2008 version of the project, which incorporates all reported bug fixes up-to-date:Let me know if you encounter any problems.

See also:
Write a Better Windows Service by Alek Davis

No comments: