This is useful when you need to ensure that an action (eg. breakpoint) occurs only when the method was invoked in the correct context. Frequently the area of interest could be invoked from several areas/contexts, the StackTrace object allows you to ensure that you are debugging the common method within the correct invokation context
StackTrace st = new StackTrace(false); var found = st.GetFrames().Any(sf => sf.GetMethod().Name.Contains("MethodName")); if (found) // This ensures that the action occurs in the correct context { if (ix == 1) // or some other condition { Trace.WriteLine("Stack Trace of where the exception occurred: " + st.ToString()); Debugger.Break(); // Forces a breakpoint here throw new MyException("Test exception"); } }
Be aware that a StackTrace object is computationally quite expensive. This technique might not work where the method being debugged is called at a high rate and which finishes processing very quickly. However, we are using it here for debugging only.
No comments:
Post a Comment