How to debug the .NET Windows Service OnStart method?

后端 未结 16 1288
离开以前
离开以前 2020-12-01 00:13

I have code written in .NET that only fails when installed as a Windows service. The failure doesn\'t allow the service to even start. I can\'t figure out how I can step int

相关标签:
16条回答
  • 2020-12-01 00:31

    As others have pointed out, you have to add a debugger break to the OnStart-Method:

    #if DEBUG
        System.Diagnostics.Debugger.Break()
    #endif
    

    Also start VisualStudio as Administrator and allow, that a process can automatically be debugged by a different user (as explained here):

    reg add "HKCR\AppID\{E62A7A31-6025-408E-87F6-81AEB0DC9347}" /v AppIDFlags /t REG_DWORD /d 8 /f
    

    (I also explained this here: https://stackoverflow.com/a/35715389/5132456 )

    0 讨论(0)
  • 2020-12-01 00:32

    It's possible to set up a companion project to the Windows Service that runs as a console app, but accesses the service methods using Reflection. See here for details and an example: http://ryan.kohn.ca/articles/how-to-debug-a-windows-service-in-csharp-using-reflection/.

    0 讨论(0)
  • 2020-12-01 00:33

    The options above did not appear to work on Windows 8.

    I have added Thread.Sleep(15000); into my OnStart() method and set a breakpoint on the next line of the code. This give me 15 seconds to attach VS debugger to my process after starting the service and allowed me to debug the OnStart() method nicely.

    0 讨论(0)
  • 2020-12-01 00:34

    It works just fine!

    protected override void OnStart(string[] args)
    {
        System.Diagnostics.Debugger.Launch();
    }
    
    0 讨论(0)
  • 2020-12-01 00:36

    One thing you could do as a temporary workaround is to launch the debugger as the first line of code in the OnStart

    System.Diagnostics.Debugger.Launch()
    

    This will prompt you for the debugger you'd like to use. Simply have the solution already open in Visual Studio and choose that instance from the list.

    0 讨论(0)
  • 2020-12-01 00:36

    You can add a line of code like this:

    System.Diagnostics.Debugger.Break()
    

    which will bring up a window prompting you to choose which debugger to use to debug, e.g. allowing you to attach with Visual Studio and step into the code.

    see:

    http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break.aspx

    0 讨论(0)
提交回复
热议问题