C# 以编程方式转储调用堆栈
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1678816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dumping the call stack programmatically
提问by RC1140
Looking for a way to programmatically dump the call stack and a .net Win Forms app when ever a section of code is hit. Its something I haven't come across before but will save me some debug time.
寻找一种在命中一段代码时以编程方式转储调用堆栈和 .net Win Forms 应用程序的方法。它是我以前从未遇到过的,但会为我节省一些调试时间。
Update: Forgot to add, how much overhead would this add to the application , i.e. would it slow it down considerably.
更新:忘记添加了,这会给应用程序增加多少开销,即它会大大减慢它的速度。
采纳答案by Ryan Cook
System.Environment.StackTrace
Will give you the current stack as a string.
将为您提供当前堆栈作为字符串。
You can also use the StackTrace
class as others have pointed out if you have more advanced needs.
StackTrace
如果您有更高级的需求,您也可以像其他人指出的那样使用该课程。
回答by Wim Hollebrandse
You can use:
您可以使用:
StackTrace callStack = new StackTrace();
And to then access a specific stack frame:
然后访问特定的堆栈帧:
StackFrame frame = callStack.GetFrame(1);
回答by Arthur
http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx
From MSDN:
来自 MSDN:
using System.Diagnostics;
StackTrace st = new StackTrace(true);
for(int i =0; i< st.FrameCount; i++ )
{
// Note that high up the call stack, there is only
// one stack frame.
StackFrame sf = st.GetFrame(i);
Console.WriteLine();
Console.WriteLine("High up the call stack, Method: {0}",
sf.GetMethod());
Console.WriteLine("High up the call stack, Line Number: {0}",
sf.GetFileLineNumber());
}
回答by Tomas Walek
Actually it wouldn't slow down your application, because the callstack information mustn't be generated, it's present during the whole processing of your code.
实际上,它不会减慢您的应用程序的速度,因为不得生成调用堆栈信息,它在您的代码的整个处理过程中都存在。