Debugging a .NET Windows Service in Vista with Visual Studio

From HowToGeek

Jump to: navigation, search

While trying to debug a Windows Service at work, I discovered a neat trick that will let you debug a service from the OnStart method, which is something you can't do by simply attaching to the process. I've written up both techniques, which will hopefully help somebody other than me.

Contents


Debugging From the OnStart Method

In order to debug a service during the OnStart method, you'll need to launch Visual Studio as administrator and open your project. You'll also need to have installed the service using the ServiceUtil command (or other installation method).

You can trigger the service to automatically launch your debugger by adding in a line of code into your OnStart method.

System.Diagnostics.Debugger.Launch();

Debugginga.NETWindowsServiceinVistawithVisualStudio1.png


This will trigger the debugger to launch as soon as you start the service up.

Debugginga.NETWindowsServiceinVistawithVisualStudio2.png


You'll be prompted to attach the debugger to the process, so click the Yes button:

Debugginga.NETWindowsServiceinVistawithVisualStudio3.png


Now you'll be able to choose from possible debuggers, but keep in mind that you'll need to have Visual Studio launched as administrator to see it in this list.

Debugginga.NETWindowsServiceinVistawithVisualStudio4.png


Once you click the Yes button, you'll be able to debug your service just like any application.

Debugginga.NETWindowsServiceinVistawithVisualStudio5.png


Attaching To a Running Service

Instead of starting the debugger during the OnStart, you can instead connect to a running service and debug that way. Make sure that you are running Visual Studio as an Administrator, and then open up the Debug \ Attach to Process menu item...

Debugginga.NETWindowsServiceinVistawithVisualStudio6.png


And then make sure to select "Show processes from all users" and "Show processes in all sessions" and click the Refresh button. Your service should show up in the list at this point.

Debugginga.NETWindowsServiceinVistawithVisualStudio7.png


Once you choose the Attach button, you'll be able to debug your service, typically by putting a breakpoint inside your timer event.

Debugginga.NETWindowsServiceinVistawithVisualStudio8.png


Enjoy!