August 16, 2013

Using StackTrace

Using StackTrace to show the first 3 lines of a stack trace in the debugger:
StackTrace st = new StackTrace(false);
st.Dump("UpdateScriptRunning Stack Trace", 3);
and the accompanying extension method:
public static class StackTraceExtender
{
  public static void Dump(this StackTrace st, string context, int numFrames)
  {
    Debug.WriteLine(context ?? "");
    string stk = st.ToString();
    string[] wanted = stk.Split(new string[] { "\r\n" }, 
                             StringSplitOptions.RemoveEmptyEntries);
    foreach (string line in wanted.Take(numFrames))
    {
        Debug.WriteLine(line ?? "");
    }
  }
}

No comments: