Simple debugging of Windows Services

So, you are writing a windows service. You want to debug it when it starts. How do you attach the debugger in time? I’ve seen lots of examples where people have implemented a Thread.Sleep() method during start-up to allow them enough time to attach to the service process. While this works it is pretty messy. I’ve also seen people add a console application that fires of a new instance of the service to get them debugging access that way. However, there is a much simpler way.

1. Launch Visual Studio with administrator rights

2. In the OnStart() method of your service, add the following line

protected override void OnStart(string[] args)
// If the service is running in debug mode then this line enables us a chance to be asked if we want the debugging service to be attached when the service is starting.

// .. rest of your code for this method here



3. Add a breakpoint to the Debugger.Launch() line.

4. Recompile your service and start it.

You will be prompted to attach the Visual Studio debugger. Your service will pause starting until you are attached and then hit your breakpoint. Much easier!