Is there an easier way to step through the code than to start the service through the Windows Service Control Manager and then attaching the debugger to the thread? It\'s ki
When developing and debugging a Windows service I typically run it as a console application by adding a /console startup parameter and checking this. Makes life much easier.
static void Main(string[] args) {
if (Console.In != StreamReader.Null) {
if (args.Length > 0 && args[0] == "/console") {
// Start your service work.
}
}
}
For trouble-shooting on existing Windows Service program, use 'Debugger.Break()' as other guys suggested.
For new Windows Service program, I would suggest using James Michael Hare's method http://geekswithblogs.net/BlackRabbitCoder/archive/2011/03/01/c-toolbox-debug-able-self-installable-windows-service-template-redux.aspx
You have two options to do the debugging.
Please refer THIS blog post that i created for the topic.
Just paste
Debugger.Break();
any where in you code.
For Example ,
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
private static void Main()
{
Debugger.Break();
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
It will hit Debugger.Break();
when you run your program.
When I write a service I put all the service logic in a dll project and create two "hosts" that call into this dll, one is a Windows service and the other is a command line application.
I use the command line application for debugging and attach the debugger to the real service only for bugs I can't reproduce in the command line application.
I you use this approach just remember that you have to test all the code while running in a real service, while the command line tool is a nice debugging aid it's a different environment and it doesn't behave exactly like a real service.
static void Main()
{
#if DEBUG
// Run as interactive exe in debug mode to allow easy
// debugging.
var service = new MyService();
service.OnStart(null);
// Sleep the main thread indefinitely while the service code
// runs in .OnStart
Thread.Sleep(Timeout.Infinite);
#else
// Run normally as service in release mode.
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]{ new MyService() };
ServiceBase.Run(ServicesToRun);
#endif
}