Stack Frame

Use of Stack Trace and Stack frame classes.
Sometimes, you want to programmatically retrieve information about the call stack at any point from within their code. You would like to determine where you are in code, or to be able to determine the sequence of procedures that your application "visited" before getting to the current procedure.

1)Clicking the "Test Procedure Stack" button calls ProcA, which calls ProcB. ProcB calls the GetFullStackFrameInfo procedure, passing in a new StackTrace object.
2)The "Test Exception Handling" button takes similar actions, but the code triggers an exception and passes that exception to the constructor for the StackTrace object.


using System.Diagnostics;

private void btnException_Click(object sender, System.EventArgs e)
{

try
{
ProcException1(1, 2);
}
catch(Exception exp)
{
GetFullStackFrameInfo(new StackTrace(exp));
}
}

private void btnStackTrace_Click(object sender, System.EventArgs e)
{
int x = 2;
ProcA(1, ref x, "Hello");
}

private void GetFullStackFrameInfo(StackTrace st)
{
int fc = st.FrameCount;

lstStackItems.Items.Clear();

for(int i = 0; i < fc - 1; i++)
{
lstStackItems.Items.Add(GetStackFrameInfo(st.GetFrame(i)));
}
}

private string GetStackFrameInfo(StackFrame sf)
{
string strParams;

MethodInfo mi;
Type typ;
string strOut = string.Empty;

mi = (MethodInfo) sf.GetMethod();

if (mi.IsPrivate)
{
strOut += "private ";
}
else if ( mi.IsPublic )
{
strOut += "public ";
}
else if ( mi.IsFamily )
{
strOut += "protected ";
}
else if ( mi.IsAssembly )
{
strOut += "internal ";
}

if ( mi.IsStatic )
{
strOut += "static ";
}

strOut += mi.Name + "(";

ParameterInfo[] piList = sf.GetMethod().GetParameters();

strParams = string.Empty;

foreach(ParameterInfo pi in piList)
{
strParams += string.Format(", {0} {1} {2}", ((pi.ParameterType.IsByRef) ? "ByRef" : "ByVal"), pi.Name, pi.ParameterType.Name);
}

if (strParams.Length > 2)
{
strOut += strParams.Substring(2);
}
typ = mi.ReturnType;
strOut += ") " + typ.ToString();

return strOut;
}
private void ProcException1(int x, int y)
{
ProcException2("Mike", 12);
}

private void ProcException2(string Name, long Size)
{
ProcException3();
}

private string ProcException3()
{
return ProcException4("mike@microsoft.com");
}

private string ProcException4(string EmailAddress)
{
throw new ArgumentException("This is a fake exception!");
}

private void ProcA(int Item1, ref int Item2, string Item3)
{
ProcB(string.Concat(Item1, Item2, Item3));
}

private void ProcB(string Name)
{
GetFullStackFrameInfo(new StackTrace());
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: