是可以安全使用的堆栈跟踪类来查找当前方法的调用者 [英] Is it safe to use the StackTrace class to find the caller of the current method

查看:116
本文介绍了是可以安全使用的堆栈跟踪类来查找当前方法的调用者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这是否是安全的,请使用以下code,以确定名称(以及可能的更多信息),调用当前执行code中的方法或对象:

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?

我都对着堆栈跟踪<的MSDN页面/ A>却发现没有提及任何可能发生的问题。

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

推荐答案

方法可以由编译器提供了不同的看法相比,你直接看code期望被内联。您可以使用一个属性,以确保你的方法是不是内联

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.
}

否则,如果的MyMethod 内联的堆栈跟踪不包含帧的MyMethod 其中的code可以依靠的人。

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

这篇关于是可以安全使用的堆栈跟踪类来查找当前方法的调用者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆