Home > Windows service > How to debug windows service

How to debug windows service

Debugging a Windows service under Visual Studio .NET is not straight forward alternative is to create a console application project and then after successful functionality with debugging use the same code in windows service.

Solution to this is that when you create new windows service project  Main() function is available in  Program.cs class.

Do following modification in Program.cs and debug your windows service normally.

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
//comment these lines while debug
//un-comment when you want to install windows service
//ServicesToRun = new ServiceBase[]
//{
//    new Service1()
//};
//ServiceBase.Run(ServicesToRun);

//comment these lines when you want to install windows service and
//un-comment when you want to debug
Service1 service = new Service1();
service.MethodCalled();//new method added wchich will be called
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

}
}

Now do following changes in Service1.cs

public Service1()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{

//comment these lines when you want to install windows service and
//un-comment when you want to debug
// MethodCalled();
}

protected override void OnStop()
{
}

public void MethodCalled()
{

//Debug will come here after adding break point write your windows service code in this method
}

Using this when you start debugging in Visual Studio debugger will come in method MethodCalled()

Found this solution at http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx by By Lee Humphries

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: