Friday, September 19, 2008

How to: Debug Windows Service in Visual Studio .NET

Debugging a Windows Service Application is a very unpleasant task because such application doesn’t run from within Visual Studio .NET. A Windows Service Application runs in the Services Control Manager context.
In order to debug a service you must start it and then attach a debugger to the process in which it is running. After that, we can place breakpoints wherever we need to because all of the standard debugging functionality of Visual Studio .NET will be available.

You can only attach the debugger to a running service. The attachment process interrupts the current functioning of your service; it does not actually stop or pause the service's processing. That is, if your service is running when you begin debugging, it is still technically in the Started state as you debug it, but its processing has been suspended.

How to attach a debugger to a Windows Service

First ensure your service is installed and is running properly by inspecting the Service windows under Control Panel/Administrative Tools. Go to your Visual Studio’s main menu and choose: Debug/Attach process to… (this is available for Visual Studio .NET 2008). From the available processes list, choose the process you want to attach a debugger to. The service’s process will have the same name as the exe file generated by the compiler for that service.


Downsides of attaching a debugger

  • You can't debug the OnStart() and Main() methods because you can only attach a debugger to a service after it has started running, which by then, the OnStart() method has already completed its execution and returned the control to the operating system.
  • You must attach the debugger each time the project is restarted.
  • This feature is not availble for Visual Studio .NET Express Edition

3 comments:

Anonymous said...

One way I've gotten around this is to add the service project to a form project/solution. The service project can then be debugged from the form project. Worked for me.

DotNetFacts said...

Thanks for your tip! I will try it.

Rourke said...

I have a workaround. You're right that you can't debug the code prior to the service launching. However you can attach while OnStart is running. Just put something like System.Threading.Thread.Sleep(30000) early in OnStart and while that 30 seconds is ticking over, attach to the process via the VS debug menu.