Setting a Breakpoint with Code
Versions: 2008,2010
Published: 10/30/2010
Code: vstipDebug0036
There will be times you want code to break when you are debugging without having to set a Breakpoint. You can do this in your code quite easily. Here is how you do it:
Compiler Directive
In C# and VB you need to set a compiler option that will only hit the breakpoint when debugging. If you don't then, in your Release code, it will continue to hit the code-based Breakpoint which is generally considered a bad thing. To do this you use the #If DEBUG compiler option. I will demonstrate this in each of the code samples.
C#
In C# you set a Breakpoint by using the System.Diagnostics.Debugger.Break() method:
VB
In VB you set a Breakpoint by using the Stop command:
And there you have it! Now you can use code to set Breakpoints. Just as an aside, Breakpoints set in this way will NOT show up in the Breakpoints Window.
Comments
Anonymous
October 29, 2010
In C/C++ you can use _CtrDbgBreak(); (which does nothing outside of debug builds, so the surrounding stuff isn't needed there). msdn.microsoft.com/.../k4wx2tde.aspx One thing to be careful of is that you don't have a SEH exception handler around the code swallowing everything as I think that prevents the breakpoint being hit. (It raises an exception and shows a crash dialog, where you can click Debug and VS handles the rest.)Anonymous
October 29, 2010
Great info Leo!Anonymous
October 29, 2010
Perhaps even more useful is to only break when already under the debugger (I often add this at the end of "last chance" exception logging): if (Debugger.isAttached) { Debugger,Break(); }