Monday, September 17, 2012

Easy way to debug a Windows Service at startup

The typical way of debugging a Windows Service, is to attach a debugger to it after it has started. This does not work very well if one needs to debug code that only executes during the startup of the Windows Service. A useful technique I have used to debug Windows Services is to launch the debugger from the Windows Service itself if a DEBUG parameter is specified. For example:

Windows Service Properties


protected override void OnStart(string[] args)
{
    // Only use this code in Debug mode.
    #if DEBUG
 
    List<string> arguments = new List<string>(args);
    if (arguments.Exists((arg) => arg.Equals("DEBUG",
        StringComparison.InvariantCultureIgnoreCase)))
    {
        // Launch Debugger if DEBUG argument is provided.
        System.Diagnostics.Debugger.Launch();
    }
 
    #endif
}

No comments: