Monday 9 June 2014

Debug a Windows Service with Visual Studio

I was just working on a Windows Service in Visual Studio 2010 and needed to debug it.  I went to the debug menu and selected "Attach to process", but the executable was greyed out.  I did a bit of Googling and found this most awesome single line of code...
System.Diagnostics.Debugger.Launch();

It tells Windows to ask if you want to debug the application, and you simply select the running version of Visual Studio and you're in the code.



If you're remote debugging then add this code to the startup of the service and it will make the service wait till you attach to it from Visual Studio (using remote debugging) before continuing...

while (!System.Diagnostics.Debugger.IsAttached)
{
    System.Threading.Thread.Sleep(1000);
}

Bosh!

No comments:

Post a Comment