C# 什么是堆栈跟踪?
可能重复:C# 什么是堆栈跟踪?,c#,stack-trace,C#,Stack Trace,可能重复: 从讨论中的评论开始,我以为我知道什么是堆栈跟踪,但我想我不知道。我用谷歌搜索了一下,但能找到一个明确的答案 stacktrace不会识别你去过哪里,它会告诉你下一步要去哪里 这里有一个小程序 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program {
从讨论中的评论开始,我以为我知道什么是堆栈跟踪,但我想我不知道。我用谷歌搜索了一下,但能找到一个明确的答案 stacktrace不会识别你去过哪里,它会告诉你下一步要去哪里 这里有一个小程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Method1();
}
private static void Method1()
{
Method2();
}
private static void Method2()
{
Random rnd = new Random();
int i = rnd.Next(0, 100);
throw new Exception();
if (i > 50)
Method3();
else
Method4();
}
private static void Method3(){ }
private static void Method4(){ }
}
}
这将生成如下所示的堆栈跟踪
at ConsoleApplication1.Program.Method2() in C:\Users\Ash Burlaczenko\Desktop\CSSD\Assignment 3\ConsoleApplication1\ConsoleApplication1\Program.cs:line 25
at ConsoleApplication1.Program.Method1() in C:\Users\Ash Burlaczenko\Desktop\CSSD\Assignment 3\ConsoleApplication1\ConsoleApplication1\Program.cs:line 17
at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Ash Burlaczenko\Desktop\CSSD\Assignment 3\ConsoleApplication1\ConsoleApplication1\Program.cs:line 12
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
尽管在异常发生时,代码可以确定将调用哪个方法,因为它知道i
的值,但堆栈跟踪没有提到未来的方法调用
堆栈跟踪告诉您代码的位置,这种想法哪里不对?堆栈跟踪显示您的位置,并假设您从当前函数正常返回,最终返回到当前函数。根据当前函数的内容,可能会有其他将首先执行的内容(即当前函数将调用但尚未调用的函数)不会显示在堆栈跟踪中(并且在输入它们之前不能/不会显示)。这是 有关详细信息,请参见我的答案 另请参见最近这个有趣的问题,该问题探讨了“等待”延续和“真实堆栈跟踪”延续之间的关系:
我想Eric的意思是,您采取的“下一步”通常是从堆栈顶部弹出时所采取的步骤,即从函数调用返回。