Jaa


How To Debug Windows Service OnStart

The article, How to: Debug Windows Service Applications details how to attach to a running process to debug a service. This works when the code you're debugging a logical issue rather than finding the root cause of an early failure when the service starts up. Debugging the OnStart method can be problematic. According to the article:

One way to work around this is to create a temporary second service in your service application that exists only to aid in debugging. You can install both services, and then start this "dummy" service to load the service process. Once the temporary service has started the process, you can then use the Debug menu in Visual Studio to attach to the service process.

After attaching to the process, you can set breakpoints and use these to debug your code. Once you exit the dialog box you use to attach to the process, you are effectively in debug mode. You can use the Services Control Manager to start, stop, pause and continue your service, thus hitting the breakpoints you've set. You would later remove this dummy service after debugging is successful.

Rather than creating a new service solely for debugging purposes, you can use the System.Diagnostics.Debugger.Launch method. In order to use this approach the service must be compiled for Debug and the PDB file must be available and preferably in the same directory as the installed service. Don't forget that you don't need a MSI to install the service. Running installutil.exe against a DLL containing an Installer for the service is sufficient.

After you install and start the service, on Vista, you are presented with the following dialog:

Debug JIT Dialog

After selecting, "Yes, debug MyNewService.exe" you will be presented with a dialog asking whether or not you want to grant or deny access. Accessing services requires administrator level access. Then, you're given the option to load the IDE:

Launch IDE

Finally, the Visual Studio .NET IDE will load and with the breakpoint set to the line with Debugger.Launch.

Debugger

Just make sure to remove this line of code before you check the service back into a source control system. This is something that should never go into a production environment. 

While writing this entry I also came across a useful post documenting five different ways to debug a Windows service:

Five Ways to Debug a Windows Service

Comments

  • Anonymous
    July 21, 2008
    PingBack from http://blog.a-foton.ru/2008/07/how-to-debug-windows-service-onstart/

  • Anonymous
    September 11, 2008
    System.Diagnostics.Debugger.Launch() works perfectly. Thanks for the tip!

  • Anonymous
    August 20, 2009
    I use the same method..but still its not working can u help me.its working for on stop break point.but not working for the break point which i kept at Onstart method

  • Anonymous
    August 20, 2009
    The comment has been removed