How to Debug OnStart of .NET Windows Services during Development
Have you ever tried to debug a .NET Windows Service during development?
Of course you can attach a debugger to the service process using Debug –> Attach to Process*. But it is practically impossible to debug the OnStart method this way.
One possible solution is to “request” a debugger in your code by using Debugger.Launch(). When you wrap this statement in a conditional precompiler directive you can control when to attach a debugger through your current build configuration:
protected override void OnStart(string[] args) { #if DEBUGGER Debugger.Launch(); #endif // Your code here... }
To use it, you can create a new build configuration and set this symbol in the build configuration settings of the project:
* Note: When the service runs under the SYSTEM user account you need to run Visual Studio “as Administrator” to see the service process in the “Attach to Process” window or attach a debugger instance to it.