Is it safe to use the StackTrace class to find the caller of the current method

只谈情不闲聊 提交于 2019-12-08 07:18:52

问题


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:


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.



来源:https://stackoverflow.com/questions/9872623/is-it-safe-to-use-the-stacktrace-class-to-find-the-caller-of-the-current-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!