Sunday, September 24, 2017

Debug Windows Services

Out of the box, one cannot debug a Windows Service easily through Visual Studio.

Making this possible via code is very easy though.

One just needs to change the code in Program.cs to

#if DEBUG
           Service1 debugInstance = new Service1();
           debugInstance.OnDebug();

           Thread.Sleep(Timeout.Infinite);
#else
           ServiceBase[] ServicesToRun;
           ServicesToRun = new ServiceBase[]
           {
               new Service1()
           };
           ServiceBase.Run(ServicesToRun);
#endif


And add an OnDebug method to the partial class that implements ServiceBase, and has the OnStart() and OnStop() methods.

  public void OnDebug()
        {
        }


This will now be your entry point into debugging your Windows Service through Visual Studio.

No comments: