How to debug a windows service

time to read 6 min | 1004 words

Usually you are told that it is not easy to debug services, but they aren't much different than normal applications, except for the security context and no desktop environment.

Here is how I build most of my services:

static void Main(string[] args)

{

    if (args.Length == 1 && args[0].ToLower() == "debug")

    {

        new MyService().DEBUG_Start();

        Thread.CurrentThread.Join();//only way to make the main thread "hung" around

        return;

    }

 

    ServiceBase[] ServicesToRun;

 

    ServicesToRun = new ServiceBase[] { new MyService () };

 

    ServiceBase.Run(ServicesToRun);

}

DEBUG_Start() merely forward the call to the OnStart() protected method and run the rest of the service.