Is it safe to use the StackTrace class to find the

2019-05-29 21:47发布

I would like to know if it is safe to use the following code to determine the name (and possibly more information) about the method or object that called the current executing code:

StackTrace stackTrace = new StackTrace();           // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

More particularly, are there any special/corner cases where accessing the frames would not work or throw exceptions?

I have looked in the MSDN page of StackTrace but found no reference to any possible issues.

1条回答
再贱就再见
2楼-- · 2019-05-29 22:05

Methods may be inlined by the compiler providing a different view compared to what you expect from directly looking at the code . You can use an attribute to make sure that your method is not inlined:

[MethodImpl(MethodImplOptions.NoInlining)]
public void MyMethod() {
  // Get the stack trace.
}

Otherwise, if MyMethod is inlined the stack trace does not contain the frame for MyMethod which your code may depend on.

查看更多
登录 后发表回答