Posted on Apr 19, 2008

Debugging windows services in .NET

The other day I was trying to test a Windows Service that I implemented for a friend. I thought to myself that this was going to be an easy endeavor. I just needed to install the service, run it, set some breakpoints, then attach its process to the debugger and that was it. Oh boy… I was SOOO wrong. It was not as easy as I thought it would be.

I cannot remember how much time I spent trying to make it work using the above approach. It was until I decided not to rely on this “supposedly clean” way for debugging .NET Windows Service applications that I was able to complete my testing, so I could tell my friend “here is the service.”

Here is what I wrote to solve my debugging problem:


static void Main()
{
#if (!DEBUG)
    System.ServiceProcess.ServiceBase[] ServicesToRun;
    ServicesToRun = new System.ServiceProcess.ServiceBase[]{
         new MyService()
    };
    System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#else
    // Debug code: this allows the process to run
    // as a non-service.
    // Put a breakpoint on the following line
    MyService service = new MyService();
    System.Threading.Thread.Sleep(
      System.Threading.Timeout.Infinite
    );
#endif
}

I know, I know, this is not pretty, but It works. At the end that’s the only thing that matters :-)

Spam Protection by WP-SpamFree