Hello, hello. If you have never written a Windows service, but you suddenly need it, then this
a small post for you.
Why is this all about?
If you started writing a service, then there is a question about debugging it. On the Internet, they mostly write about the way in which the
debugger is
connected to an already running service process , about which alternative I want to tell. Because a service is not an ordinary Windows process, just running it from Visual Studio will fail.
Installation service
When you try to start you will be shown a message that, they say, the service can not start and you need to use
installutil.exe
to install it.

To install the service, you need a Visual Studio console, which is located along the path
→ → Visual Studio 2008 → Visual Studio Tools → Visual Studio 2008 Command Prompt
(depending on the version of VS installed, the path may differ)
After starting the console, go to the directory where your service is going in
Debug
mode and install it:
installutil.exe /i < >
More you
installutil.exe
not required. For convenience, run the Windows service management console:
services.msc
Now you can close the Visual Studio console.
We proceed to the most interesting :-)
')
Debugging Service
Method number 1 (connect debugger)
- Start the service using the Windows Services Management Console.
- In Visual Studio, select
Tools → Connect To Process
in the dialog box that appears, select the name of the service process and click the Attach
button
After that, you can set breakpoints and debug the service.
This method has a drawback: without additional tweaks, it will not be possible to debug the code located in the
OnStart
handler.
Method number 2 (connecting the debugger from the source code)
In the code of the
program.cs
module, immediately after the start of the
Main()
method we add the following:
#if DEBUG
System.Diagnostics. Debugger .Launch();
#endif
This code connects the debugger to the process and is compiled only in
DEBUG
mode. Now, to debug a service, you need to start it not from Visual Studio, but using the service management console (or
net start
commands). Immediately after launching, the debugger selection dialog box will appear:

Choose a running instance of Visual Studio, click
Yes
and enjoy debugging!
Method number 3 (run with command line parameters)
suggested by
gwynbleiddThere is another way - to provide for the possibility of starting the service as a console application. For example, on the command line, pass / console, and if this flag is set, start the application as a console, if not, as a service.
The advantages of this approach:
It is very easy to debug, in essence, like a regular console application. Debug information can be output to the console.
Thank you
komr for help in debugging text :-)