Custom Software Apps & SharePoint Consulting

Windows Service Development Trick

Windows Services are a bit of a pain to develop. They can’t be run through the debugger, and by default they can’t be run on the command line either. They have to be installed and then run. When debugging, you have to install the service, restart the service, and then attach the debugger. Ouch.

(I found this trick online, but I can’t find the URL again, so my apologies to anonymous internet dude who suggested this technique)

In your main method, change the generated default to this:

static void Main(string[] args)
{
try
{
if( args.Length == 1 && args[ 0 ].Equals( “console” ) )
{
new MyService().ConsoleRun();
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run( ServicesToRun );
}
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

In the service code itself, add the following method:

public void ConsoleRun()
{
Console.WriteLine( “Starting…” );
OnStart( null );
Console.WriteLine( “Ready (any key to exit)” );
Console.ReadLine();
OnStop();
Console.WriteLine( “Stopped.” );
}

Now you can build your service, then run it from a command line by adding the command line argument “console”. Stop the service just by hitting carriage return at the command line. You still have to manually attach the debugger, but it reduces the cycle time to diagnose and fix issues significantly.

Share this post with your friends

Skip to content