Easier way to debug a Windows service

后端 未结 28 1621
春和景丽
春和景丽 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:27

    If I want to quickly debug the service, I just drop in a Debugger.Break() in there. When that line is reached, it will drop me back to VS. Don't forget to remove that line when you are done.

    UPDATE: As an alternative to #if DEBUG pragmas, you can also use Conditional("DEBUG_SERVICE") attribute.

    [Conditional("DEBUG_SERVICE")]
    private static void DebugMode()
    {
        Debugger.Break();
    }
    

    On your OnStart, just call this method:

    public override void OnStart()
    {
         DebugMode();
         /* ... do the rest */
    }
    

    There, the code will only be enabled during Debug builds. While you're at it, it might be useful to create a separate Build Configuration for service debugging.

提交回复
热议问题