Home .NET Easy debugging of Windows services

Easy debugging of Windows services

by admin

Debugging Windows Service applications is not as trivial task as it seems. The problem is that it is impossible to use standard Visual Studio tools such as breakpoints and other useful tools when debugging this type of applications. It is because Windows Service application cannot be launched by F5 directly from Visual Studio. Still, MSDN offers us several ways to debug them. Many developers probably didn’t even encounter them until they started building their first service. These are the use of event logging and connecting to the process Both of these methods are well described in MSDN but they only allow you to debug a service which is already running. Because of this, you can’t test the code that makes the service itself start in the OnStart() method.
Below I want to tell you how you can bypass this restriction and test your service as a normal console application. And hence, take advantage of all that Visual Studio has to offer for this.
First we need to create a new project. Let’s call it TestWinService.
Easy debugging of Windows services

Since this is a service, let’s add an installer to it right away. Right click on the empty area of the just opened file and select Add Installer.
Easy debugging of Windows services

Now let’s add a console project to our solution, from which we will actually debug our service. Right after creating the new project, we will add two links to it. One to our service, TestWinService, the other to the System.ServiceProcess needed to call the service.
Easy debugging of Windows services
Now comes the fun part. To debug the code that starts the service, we will need to create a new thread that will do all the work. We will also need two methods: Start() and Stop() to start and stop it. And, accordingly, call them in methods of starting and stopping the service. We end up with something like this.
Easy debugging of Windows services

You can see that we added a test line and put a breakpoint on it.
Now let’s add some code to the console application, which will emulate starting and stopping the service. We should get something similar to the picture below.
Easy debugging of Windows services

You’re all set! All that’s left is to press F5 and make sure that the debugger stops at the test line.
Easy debugging of Windows services

With this method, debugging services becomes no more difficult than debugging a normal console application. I hope this is useful to someone.

You may also like