19

Is it possible to specify a breakpoint in Visual Studio 2010 that hits only if the calling methods up the call stack meet some specific condition? For example, and most likely, method name.

I am ideally looking for a solution in Visual Studio itself such as the conditional breakpoint, but I'll settle for testing method names up the stack in code and having a coded breakpoint.

What I'm trying to achieve is to cut out calls from a specific caller.

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187

2 Answers2

22

Right click the breakpoint, choose "Condition" and use something like this:

new System.Diagnostics.StackTrace().ToString().Contains("YourMethodName")
František Žiačik
  • 7,511
  • 1
  • 34
  • 59
  • This will string the entire stack trace, making it quite greedy. Is it possible to iterate, say, the last 5 callers and test their names whilst still plugging the code into the "Condition..." snippet? – Adam Houldsworth Apr 04 '11 at 15:16
  • 1
    As the condition must be a one-liner, you could use `GetFrame(index)` joined together with `||`, but it would make it even less effective. – František Žiačik Apr 04 '11 at 15:19
  • Also, you can't use lambdas in the condition. – František Žiačik Apr 04 '11 at 15:21
  • But, anyway, the main performance problem here is with creating the StackTrace object, not with "string-ing" it. :) It's up to you if it is acceptable. If not, you can always test it in your code and use `Debugger.Break`. – František Žiačik Apr 04 '11 at 15:24
  • 1
    I never implied there was a performance problem. I was highlighting the fact that calling `ToString` on it sticks the entire stack frame into one string, so I have no control at that point in stating that I'm only interested in the immediate caller, or the 5th caller. Hence I said it was greedy, as in, checks the entire stack frame not just the parts I'm interested in. – Adam Houldsworth Apr 04 '11 at 16:15
  • 1
    I'll mark yours as the answer for the further information about conditional breakpoints, but because I need good control over the state of the stack I will have to implement it physically in the code. I'm going to play with making a static helper that gives me a one-liner that I can put in a conditional breakpoint :-) – Adam Houldsworth Apr 04 '11 at 16:18
  • 6
    @Adam BTW, if you are only interested in the immediate caller, replace "new System.Diagnostics.Stack **Trace** ()" with "new System.Diagnostics.Stack **Frame** ()". If you're interested in the 5th caller, replace it with "new System.Diagnostics.Stack **Frame(4)** " – Omer Raviv Apr 04 '11 at 17:56
4

The StackTrace class should give you what you need.

StackTrace stackTrace = new StackTrace();           
StackFrame[] stackFrames = stackTrace.GetFrames(); 
BrandonZeider
  • 8,014
  • 2
  • 23
  • 20