Wednesday, May 13, 2009

Debugging a Windows Service

When creating windows services using .Net we always face problems while debugging it, since the attach process approach of debugging is on my opinion useless. The following is code snippet i found on internet that will enable windows service debugging and will make it running like any other desktop application.


1- Create a windows service.



2- Put this code at Program.cs on Main method:


Service1 obj= new Service1();
obj.start();
do
{
System.Threading.Thread.Sleep(1000);
} while (true);


The new main method will look like this:

static void Main()
{
Service1 email = new Service1();
email.AnyMethod();
do
{
System.Threading.Thread.Sleep(1000);
} while (true);
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}



Where Service1 that you create intance from it your service name, and AnyMethod is any method that you create inside the service class.


When you run the service you will notice that the debugging is breaking at the AnyMethod that you just created at your service.

No comments: