How to debug the .NET Windows Service OnStart method?

后端 未结 16 1290
离开以前
离开以前 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:25

    Once you have a service that is installed using installutil.exe, you can alter the Start Parameters to jump into the debugger if the service is started:

    enter image description here

    When you manually start the service with the parameter -debugWithVisualStudio (or simply -d), it will automatically detect the correct project, and fire up the interactive debugger in Visual Studio:

    enter image description here

    To support this functionality, change the service's OnStart() function:

    /// 
    ///     Executed when the service is started.
    /// 
    /// Command line arguments.
    protected override void OnStart(string[] args)
    {
        try
        {
            //How to debug when running a Windows Service:
            // 1. Right click on the service name in Windows Service Manager.
            // 2. Select "Properties".
            // 3. In "Start Parameters", enter "-d" (or "-debugWithVisualStudio").
            // 4. Now, when you start the service, it will fire up Visual Studio 2012 and break on the line below.
            // 5. Make sure you have UAC (User Access Control) turned off, and have Administrator privileges.
    #if DEBUG
            if (((ICollection)args).Contains("-d")
                || ((ICollection)args).Contains("-debugWithVisualStudio"))
            {
                Debugger.Launch(); // Launches VS2012 debugger.
            }
    #endif
            ShellStart(args);
            base.OnStart(args);
        }
        catch (Exception ex)
        {
            // Log exception here.
        }
    }
    

    (optional) If you want to narrow down to the exact line of code where the service is throwing an error, switch on exceptions from the Visual Studio menu DEBUG .. Exceptions. When you continue debugging, it will break on the exact line that is throwing the exception.

    enter image description here

提交回复
热议问题