Tuesday, October 11, 2011

Simple way to debug Windows Service startup


If you come to situation that you need to debug the startup of your Windows Service here's a simple and dirty (and stupid) method that helps in most situations.
This could be used in situation where your service immediately starts and stops.
Windows Services reports a message like this:

The "serviceName" service on Local Computer started abd then stopped. Some services stop automatically if they are not in use by other services or programs.
Usually, to debug a service you'll need to setup the breakpoint in your code, attach to the process from Visual Studio, and debug upon hitting the breakpoint.
Problem is if your service immediately exits and your don't have time to attach the debugger.
Simple, stupid way to debug it is to... guess what?... add a Thread.Sleep() as the first line in your code.
Sample, service acting as a WCF Host and it's OnStartup() method:


protected override void OnStart(string[] args)
{
   System.Threading.Thread.Sleep(30000);
   myHost= new ServiceHost(typeof(MyService)); //set breakpoint here
   myHost.Open();
}



Now you have enough time to attach the debugger from Visual Studio and you don't have to use Windows Debugger Tools or similar advanced methods.

No comments: