Tuesday 30 March 2010

Call Stack based Breakpoint

Well, this is rather basic stuff, but anyway it's something I'd never done before and could be useful to someone out there.

The other day, while doing some debugging with Visual Studio I wanted to set a Conditional Breakpoint in one method that would break or not depending on what method did the call.

Well, it would make sense to have an option in the Breakpoint Menu or in the Breakpoint Condition window that would let you select that, a method in your Call Stack, but unfortunately there's not such option. I felt a bit lost at first, I'd only used Conditional Breakpoints for basic conditions such as argument1 = "troublesome string" or things like that, but well, the TextBox in the Breakpoint Condition Window lets you write any expression, that means, it's not just comparing two variables there, I can create new objects and so on... so, given that we have the StackTrace class, this is so simple as writing something like this:

new StackTrace().GetFrame(1).GetMethod().Name == "Method2"

you can go up the CallStack as you please by selecting the appropiate StackFrame...

I've tried to test this with lovely SharpDevelop, but I'm getting an exception when trying to set the Conditional Breakpoint...

I've used this dummy code for my testing.
Method1 is invoked both from Method2 and from Main, we only want to break when the immediate caller is Method2...



No comments:

Post a Comment