Can I trace the Call Stack at any particular point without breaking into the debugger?

Platform: WinForms| Category: Debugging

Yes, there are classes in the framework that will provide you call stack information that you can trace to the output:


[C#]
		public static void TraceCallStack()
		{
			StackTrace st = new StackTrace(1, true);
			StackFrame sf = st.GetFrame(StackTrace.METHODS_TO_SKIP);
			if (sf != null)
			{
				MethodBase mb = sf.GetMethod();
				StringBuilder sb = new StringBuilder();
				sb.Append(mb.ReflectedType.Name);
				sb.Append('.');
				sb.Append(mb.Name);
				sb.Append('(');
				bool first = true;
				foreach (ParameterInfo pi in mb.GetParameters())
				{
					if (!first)
						sb.Append(', ');
					first = false;
					sb.Append(pi.ParameterType.Name);
					sb.Append(' ');
					sb.Append(pi.Name);
				}   
				sb.Append(');');

				int n = StackTrace.METHODS_TO_SKIP+1;
				sf = st.GetFrame(n);
				if (sf != null)
				{
					sb.Append(' called from ');

					do 
					{
						mb = sf.GetMethod();
						sb.Append(mb.ReflectedType.Name);
						sb.Append('.');
						sb.Append(mb.Name);
						sb.Append(':');
						sf = st.GetFrame(++n);
					}
					while (sf != null);
                        
				}

				Trace.WriteLine(sb.ToString());
			}
		}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.