1

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.

https://docs.microsoft.com/en-us/dotnet/framework/windows-services/how-to-debug-windows-service-applications

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:-

  1. have the project open in VS2017

  2. start cron.exe from cmd line; the service should be Running

    the cmd window will say "Press any key to stop the service"

  3. set breakpoints; they are not disabled!

    you can even set a breakpoint in OnStart() and OnStop()

  4. [>] Start with debug

    breakpoints will be hit!

  5. to stop debugging press any key in cmd window

terrym
  • 11
  • 1

1 Answers1

0

There is anotehr way. I don't know it it will work for Windows Service.
Put some where in your code from where you want to start debuging

System.Diagnostics.Debugger.Launch();

After that you may start your service via service manager or any other way you usally do this. Than you will have a promt to select a debuger. Choose an instance of Visual Studio with opened project.

You may not see your instance of Visual Studio until you launch it with admin rights.

Ruslan F.
  • 4,550
  • 3
  • 19
  • 36