Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Let your application ask you to attach to a debugger rather than you do it manually

0.00/5 (No votes)
1 Dec 2009 1  
Sometimes you need to debug an application in a point where it’s difficult to attach debugger manually. For applications which you can’t run directly from Visual Studio (say windows service), you usually use attach process to visual studio to debug. So if you have a windows service running (with...
Sometimes you need to debug an application in a point where it’s difficult to attach debugger manually. For applications which you can’t run directly from Visual Studio (say windows service), you usually use attach process to visual studio to debug. So if you have a windows service running (with debug mode dlls) then you can attach the process to your visual studio to debug. But if your windows service has some code in the constructor that you need to debug then how would you debug the code? When you’ll attach the windows service the constructor code is already executed.
There a way in dot net to prompt to attach a debugger from the running application. If you write the following code in any place in your code then when the application will find this statement the application will prompt you to attach a debugger.

System.Diagnostics.Debugger.Break();

Then if you attach the application with visual studio with code (with correct build version) you’ll find yourself in debug mode. But remember that this statement needs to be removed from code before release build. This is because this statement will be compiled with code even with release build. To make sure you have not put that code accidentally in your release build you can put a preprocessor directive like below:

#if DEBUG<br />
System.Diagnostics.Debugger.Break();<br />
#endif<br />

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here