Easier way to debug a Windows service

后端 未结 28 1568
春和景丽
春和景丽 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 DEBUG
        System.Diagnostics.Debugger.Break();
    #endif
    
    0 讨论(0)
  • 2020-11-22 16:27
    static class Program
    {
        static void Main()
        {
            #if DEBUG
    
            // TODO: Add code to start application here
    
            //    //If the mode is in debugging
            //    //create a new service instance
            Service1 myService = new Service1();
    
            //    //call the start method - this will start the Timer.
            myService.Start();
    
            //    //Set the Thread to sleep
            Thread.Sleep(300000);
    
            //    //Call the Stop method-this will stop the Timer.
            myService.Stop();
    
             #else
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new Service1() 
            };
    
            ServiceBase.Run(ServicesToRun);
             #endif
        }
    }
    
    0 讨论(0)
  • 2020-11-22 16:30

    I also think having a separate "version" for normal execution and as a service is the way to go, but is it really required to dedicate a separate command line switch for that purpose?

    Couldn't you just do:

    public static int Main(string[] args)
    {
      if (!Environment.UserInteractive)
      {
        // Startup as service.
      }
      else
      {
        // Startup as application
      }
    }
    

    That would have the "benefit", that you can just start your app via doubleclick (OK, if you really need that) and that you can just hit F5 in Visual Studio (without the need to modify the project settings to include that /console Option).

    Technically, the Environment.UserInteractive checks if the WSF_VISIBLE Flag is set for the current window station, but is there any other reason where it would return false, apart from being run as a (non-interactive) service?

    0 讨论(0)
  • 2020-11-22 16:32

    The best option is to use the 'System.Diagnostics' namespace.

    Enclose your code in if else block for debug mode and release mode as shown below to switch between debug and release mode in visual studio,

    #if DEBUG  // for debug mode
           **Debugger.Launch();**  //debugger will hit here
           foreach (var job in JobFactory.GetJobs())
                {
                    //do something 
                }
    
    #else    // for release mode
          **Debugger.Launch();**  //debugger will hit here
         // write code here to do something in Release mode.
    
    #endif
    
    0 讨论(0)
提交回复
热议问题