Search code examples
.netdebuggingbreakpointsvisual-studio-debugging

Hit a breakpoint when there is certain method in call stack


I want a breakpoint to be hit when there is a certain method in the call stack. Can I do this somehow with the Visual Studio debugger?

I want to be sure my breakpoint will be hit when the code is called from certain methods, but not others.

For example we have two call stacks:

DBReadRecord()
GetRecord()
ActivityMonitor()

and

DBReadRecord()
GetRecord()
UserButtonDown()

I want a breakpoint in DBReadRecord to be hit only when it is called from the UserButtonDown() method and not from the ActivityMonitor() method.

I am using Visual Studio 10 and .Net 3.5.


Solution

  • You could also do some reflection-based hacking (for example, Express editions seem not to have advanced breakpoint functionalities):

        void Foo()
        {
            Foo2();
        }
        void Foo2()
        {
            var trace = new StackTrace();
            if (trace.GetFrames().Reverse().FirstOrDefault(f => f.GetMethod().Name == "Foo") != null)
                Debugger.Break(); // it lives under System.Diagnostics namespace
        }
        void Test()
        {
            Foo2(); // doesn't break here
            Foo(); // break here
        }
    

    And with your particular methods:

    Foo DBReadRecord()
    {
         var trace = new StackTrace();
         if (trace.GetFrames().Reverse().FirstOrDefault(f => f.GetMethod().Name == "UserButtonDown") != null)
             Debugger.Break();
    }
    

    Note that it greatly affects performance, so it's only temporary solution for strange debugging situations.

    Also, remember that it works best in Debug configurations, I do not know what optimizations may occur that effect in method not being in StackTrace, but such thing can happen when optimizations are turned on.