I am writing a C# Windows Service to manage two System Services that will help prevent Microsoft from upgrading W10AU (Anniversary Update) to W10CU (Creators Update). Recently Microsoft "made an error" and forced updates from v1607 to v17xx even if the user has a Metered Con-nection and had updates disabled or delayed or blocked.
I first wrote a simple C# service 'CronService' based on a tutorial. I have it working, but would like to be able to debug in VS2017. I have debugged DLLs before by loading the DLL, setting breakpoints in the code and then doing 'Run with debug'. This is harder.
This is not as easy as it appears! If you follow the above instructions you will find all breakpoints are disabled "Breakpoint will not be hit. Symbols are not loaded." If you look further, you will find that you have to jump thru hoops by writing another dummy service or ??
Easier way to debug a Windows service
Following one of the suggestions worked for me. Instead of
public static void Main() {
ServiceBase.Run(new CronService());
}
you code Main() as
public static void Main() {
if (Environment.UserInteractive) {
RunInteractive(new CronService());
} else {
ServiceBase.Run(new CronService());
}
}
then add a function RunInteractive() which you can get from the above link. This method uses Reflection to invoke OnStart() and OnStop().
You still need to compile, install and start the service in the normal way. To debug, follow these steps:-
have the project open in VS2017
start cron.exe from cmd line; the service should be Running
the cmd window will say "Press any key to stop the service"
set breakpoints; they are not disabled!
you can even set a breakpoint in OnStart() and OnStop()
[>] Start with debug
breakpoints will be hit!
to stop debugging press any key in cmd window