Wednesday, April 16, 2008

Handy tip for debugging a Windows Service

Debugging a Windows Service is always a pain. You can't run a service like a regular application, you have to run it from Windows Service Control Manager (SCM) and then have your debugger attach to the process while it's running. The problem is that it's difficult to debug problems with the service startup as the debugger can't attach to the service in time.

I came across a tip on the .NET Tip of The Day site, "How to debug Windows Service startup". Basically, you just add a line that calls Debugger.Launch() or Debugger.Break() in your startup code. When your code hits one of those lines, the Visual Studio Just-In-Time Debugger dialog will be invoked and you can select your debugger to handle the error. That will allow you to continue along in the code and debug until the cows come home.

That works better than a service debugging tip I posted a couple of years back, calling the Sleep API in your startup code to allow enough time to attach a debugger to the service. That was a hack, this is much cleaner.

All in all, I still prefer to separate the functional code from the service specific code. I can then run that code from a desktop app, making it much easier to debug. That works about 99.9% of time. Every now and then, I do need to run the actual service code and the Debugger.XXXX() calls will make that task much easier.

1 comment:

  1. Awesome. Until now, my best trick was to engineer a delay into OnStart to give me time to manually attach.

    I work with a lot of remoting services at my day job. Our host service performs some priming of the mainframe connection pool. There is certain logic, are certain processes, that sometimes, you really just can't separate from the service itself. I wish I'd known about Debugger.Launch() a year ago.

    Actually, allow me to correct that statement. I knew the method existed, had no idea what it did.


Note: Only a member of this blog may post a comment.