Question Debugging a C# Windows Service.

baylf2000

Member
Joined
Jan 7, 2023
Messages
9
Programming Experience
10+
I'm just getting started on my first Windows Service in C#. I've found some nice tutorials, and following those I've created a "Windows Service (.NET Framework)" project. However, the first question I have is how debugging is done on these types of projects? It initially looks like I have to compile and install the service every time I want to test my code. There doesn't seem to be any way to run the code in the IDE for testing because it's a service.

Am I missing something, or is there any way around this? Any info would be appreciated.
 
The traditional answer: Most old school Windows service writers allow their service to be run either as a regular console program or as a service depending on what command line parameter is used. So while still in development, they just pass in the magic flag to run as as console app rather than as a service.

The modern answer: You should be using unit tests to test the functionality of all your components. You shouldn't be debugging the service. You should be debugging the unit tests. The service just acts as a shell and entrypoint.

Anyway, with both of those answers above, there are still times when you really need to debug a running service because running as a console app, or running the unit tests doesn't completely replicate the environment of running as a particular service identity that may not have the full permissions that you as developer may have. That is when you use the "Attach to Process" menu option in Visual Studio or WinDbg. If the thing that you are trying to debug is part of the service initialization/start up, then things get a little harder. What my team used to do was have registry key or command line flag which signaled the code to display a message box, or delay for 5 seconds as the second thing it does -- reading the registry or checking the command line was the first thing.
 
Add a public OnStart method to your implementing class and call the private onstart from it, then use

#if debug
...
#endif

Around a block of code that calls the public OnStart directly instead of ServiceBase.Run
 
Also no need to uninstall/reinstall the service - just stop the service in Windows Services Manager, recompile and start again in SM.
 
Note that would only work if the service had been installed so the service is configured such that the exe was in the compiler output folder (bin\debug etc). You can stop a service, replace the exe and start it to perform an upgrade, so I think John might have meant publish (build an exe and overwrite the service exe in eg c:\program files\... with the new version) where he said compile
 
I meant install it with Installutil directly from build folder during development/debugging. You have to stop the running service process in order to be able to build again, since the .exe in build folder is then locked when it is running.
 
Back
Top Bottom