Debugging windows services in .NET

April 19th, 2008

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 :-)

programming | Comments | Trackback

Leave a Reply

  1.  
  2.  
  3.  
  4. XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
  5. Spam Protection by WP-SpamFree

You can keep track of new comments to this post with the comments feed.

 

April 2008
M T W T F S S
    May »
 123456
78910111213
14151617181920
21222324252627
282930  

Categories

Archives

Tags