In part 1 of this series I mentioned debugging a windows service was a little different than normal debugging of an application. Today we’ll look into how you can debug your windows service.
First, open Visual Studio and have your project loaded, if it’s not already there. Now go over to the MMC (as I described in part 3) and make sure it’s logging events.
Now comes the neat part. Under the Debug menu in Visual Studio, select “Attach to process…”. When the dialog below appears, you will need to check the “Show processes from all users” and “Show processes in all sessions” boxes. Now your list should update correctly.
Scroll down and look for the process with the same name as your executable, in my case it was TimeLogger.exe. Click on it, and the click the “Attach” button in the lower left.
If all went well Visual Studio should shift to “Run” mode. Your code will be locked (sorry, no edit continue with windows services). But you can go in and create breakpoints, as I’ve done here (click on the pic to see a larger version of it):
Now sit back and wait a minute, when our service fires the _timer_Elapsed event it will fall into the standard debug mode you’re used to, as you can see below.
In the screen above you can see where I took one step and am now on the line of code “string message =…”. I have access to my locals, as well as the call stack and other debugging tools. From here I can do the normal debug tasks, including stepping or just hitting F5 to continue.
When you are done debugging and are ready to disconnect from the service, simply return to the Debug menu and this time pick “Stop Debugging” (or hit Shift+F5). Visual Studio disconnects you from the running service and returns you to normal code editing mode.
Resetting for another test is still a bit painful. You’ll want to stop your service, then in your Visual Studio Command Prompt window run InstallUtil, this time with the /u option to uninstall it. (instalutil /u timelogger.exe). Then you can build, then reinstall your service.
I said this yesterday, but I want to stress it again. If you are developing under Vista, it is vitally important you run VS Command Prompt as the Administrator (simply right click on the menu option and pick run as administrator). If you don’t do this, instalutil will fail every time.
And that’s how you debug an windows service. It’s not really that difficult, now that you know the steps involved.