Pages

Tuesday, December 1, 2009

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

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
System.Diagnostics.Debugger.Break();
#endif  

3 comments:

  1. Thank you for providing help on c#. because i have need of it. be continue.

    ReplyDelete
  2. Debugging in Java is quite easy in Eclipse rather than Net beans. I found debugging feature of Eclipse quite useful than Net beans.

    ReplyDelete
  3. Thank you for such a fantastic blog. Where else could anyone get that kind of info written in such a perfect way. I like concept of your post. Very creative post. Best of luck and waiting for some new ideas.
    how to increase website traffic

    ReplyDelete

Note: Only a member of this blog may post a comment.