问题
Possible Duplicate:
CallStack determines where you are going next?
Started from the comment in this question, I thought I knew what a Stack Trace was but I guess I didn't. I've Googled it but could find a clear answer.
@asawyer says
The stacktrace doesn't identify where you've been, it tells you where you are going next.
Here is a little program
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(){ }
}
}
This produces a Stack Trace like this
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()
Although at the time of the exception the code could work out which method would be called as it knows the value of i
the Stack Trace mentions nothing about the future method calls.
Where am I going wrong with the idea that a Stack Trace tells you where the code has been?
回答1:
A stack trace shows where you've been, and assuming you return normally from the current function, where you'll eventually go back to. Depending on the content of the current function, there may be other things that will be executed first (i.e., functions the current function will call, but hasn't yet) that don't show up in the stack trace (and can't/won't until you've entered them).
回答2:
This is a duplicate of
The call stack does not say "where you came from", but "where you are going next"?
See my answer there for details.
See also this interesting recent question that explores the relationship between "await" continuations and "real stack trace" continuations:
C# await vs continuations: not quite the same?
来源:https://stackoverflow.com/questions/9877146/what-is-a-stack-trace