Easier way to debug a Windows service

后端 未结 28 2044
春和景丽
春和景丽 2020-11-22 15:36

Is there an easier way to step through the code than to start the service through the Windows Service Control Manager and then attaching the debugger to the thread? It\'s ki

28条回答
  •  梦谈多话
    2020-11-22 16:25

    I like to be able to debug every aspect of my service, including any initialization in OnStart(), while still executing it with full service behavior within the framework of the SCM... no "console" or "app" mode.

    I do this by creating a second service, in the same project, to use for debugging. The debug service, when started as usual (i.e. in the services MMC plugin), creates the service host process. This gives you a process to attach the debugger to even though you haven't started your real service yet. After attaching the debugger to the process, start your real service and you can break into it anywhere in the service lifecycle, including OnStart().

    Because it requires very minimal code intrusion, the debug service can easily be included in your service setup project, and is easily removed from your production release by commenting out a single line of code and deleting a single project installer.

    Details:

    1) Assuming you are implementing MyService, also create MyServiceDebug. Add both to the ServiceBase array in Program.cs like so:

        /// 
        /// The main entry point for the application.
        /// 
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new MyService(),
                new MyServiceDebug()
            };
            ServiceBase.Run(ServicesToRun);
        }
    

    2) Add the real service AND the debug service to the project installer for the service project:

    enter image description here

    Both services (real and debug) get included when you add the service project output to the setup project for the service. After installation, both services will appear in the service.msc MMC plugin.

    3) Start the debug service in MMC.

    4) In Visual Studio, attach the debugger to the process started by the debug service.

    5) Start the real service and enjoy debugging.

提交回复
热议问题