Debugging a Windows Services

Have you ever had this message when writing a windows service in Visual Studio?

Cannot start service from the command line or a debugger.  A Windows Service must first be installed (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative tool or the NET START command.

I was a bit surprised the first time I hit the debug button in Visual Studio and ended up having to manually attach to the service every time I wanted to debug it.  After doing this over and over again, I learned a nice little trick. I like to put inside a lot of windows services I write as it easily enables me to get past that pesky error and debug straight from the IDE.

// If the debugger is attached, the program runs inline rather
// than it being run as a service.
MyService serviceToRun = new MyService();

#if DEBUG
if (Debugger.IsAttached)
{
    serviceToRun.Start(args);

    while (Debugger.IsAttached)
    {
        Thread.Sleep(1000);
    }
}
else
#endif
{
    ServiceBase.Run(new[] { serviceToRun });
}

Essentially after the program executes, it checks if the debugger is attached.  If it is, rather than running as a service it calls directly into the service to execute and continually checks for the debugger to detach.  Once it has the program ends. The conditional compile directive ensures that this behavior will no longer be possible once a Release build is made.

The Start method is a public method that simply calls to the overriden OnStart method for the service.

You can see a full VS solution on my BitBucket repository.

Advertisements

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