📜 ⬆️ ⬇️

Convenient debugging of Windows services

Debugging Windows Service applications is not as trivial as it seems. The problem is that when debugging this type of application you cannot use standard Visual Studio tools such as breakpoints and other useful tools. This is due to the fact that the Windows Service application cannot be launched via F5 directly from Visual Studio. Nevertheless, MSDN offers us several ways to debug them. Most likely, many developers did not even come across them until they began to create their first service. This is the use of entries in the event log and connection to the process . Both of these methods are well described in MSDN, but they allow you to debug only a service that is already running. Because of this, the code that starts the service itself, in the OnStart () method, cannot be tested.

Below I want to talk about the way in which you can bypass this limitation, and test your service as a regular console application. And, therefore, take advantage of all that offers us for this Visual Studio.

First we need to create a new project. Let's call it TestWinService.

image
')
Because this service, immediately add to it the installer. Right-click on the empty area of ​​the newly opened file and select Add Installer.

image

Now we will add to our solution a console project, from which we, in fact, will debug our service. Immediately after creating a new project, add two links to it. One to our service, TestWinService, the other to System.ServiceProcess necessary to call the service.

image

Now the fun begins. To debug the code that starts the service, we will need to create a new thread, which will do all the necessary work. And also two methods - Start () and Stop () for its start and end. And, accordingly, we will call them in the methods of turning the service on and off. The result will be something like this.

image

It can be seen that we added a test line and put a breakpoint on it.
Now we will add a code to the console application that will emulate the start and stop of the service. We should have something like this in the picture below.

image

All is ready! It remains only to press F5 and make sure that the debugger stopped at the test line.

image

Using this method, debugging services is no more difficult to debug a regular console application. I hope it is useful to someone.

Source: https://habr.com/ru/post/127828/


All Articles