如何告诉编译器忽略堆栈跟踪中的方法?
是否有任何属性可以应用于样板方法,以便此类方法不会出现在堆栈跟踪中?我有很多这样的东西,在某些情况下,它们有好几层深。这只是乱七八糟的事情。
示例代码:
class Program
{
public static void ThrowMe()
{
throw new NotImplementedException();
}
public static void HideMe()
{
ThrowMe();
}
static void Main(string[] args)
{
try
{
HideMe();
}
catch (Exception e)
{
}
}
}
这会抛出此堆栈跟踪:
位于 C:\Projects\XXX\Testing Sandbox\ConsoleTesting\Program.cs 中的 Spork.Program.ThrowMe():第 58 行
位于 C:\Projects\XXX\Testing Sandbox\ConsoleTesting 中的 Spork.Program.HideMe()\Program.cs:第 64 行
位于 C:\Projects\XXX\Testing Sandbox\ConsoleTesting\Program.cs 中的 Spork.Program.Main(String[] args):第 70 行
Are there any attributes I can apply to boilerplate methods so that such methods do not appear in stack traces? I've got a lot of them and in some cases they are several levels deep. It's just cluttering things.
Example code:
class Program
{
public static void ThrowMe()
{
throw new NotImplementedException();
}
public static void HideMe()
{
ThrowMe();
}
static void Main(string[] args)
{
try
{
HideMe();
}
catch (Exception e)
{
}
}
}
This throws this stack trace:
at Spork.Program.ThrowMe() in C:\Projects\XXX\Testing Sandbox\ConsoleTesting\Program.cs:line 58
at Spork.Program.HideMe() in C:\Projects\XXX\Testing Sandbox\ConsoleTesting\Program.cs:line 64
at Spork.Program.Main(String[] args) in C:\Projects\XXX\Testing Sandbox\ConsoleTesting\Program.cs:line 70
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将 Console.WriteLine(e) 放入 catch 块中。切换到发布版本并按 Ctrl+F5。您将看到以下内容:
请注意,HideMe() 方法在堆栈跟踪中不可见。任务完成了。
方法调用未显示在跟踪中,因为 JIT 优化器内联了该方法:这是在堆栈跟踪中隐藏方法的唯一方法。
这不是你可以很好控制的东西,该方法必须“小”并且本身不抛出任何异常。否则,这通常被认为是一个问题,而不是一个功能。很难弄清楚如何从 A 到 B 进行编码。
Put Console.WriteLine(e) in the catch block. Switch to the release build and press Ctrl+F5. You'll see this:
Note that the HideMe() method is not visible in the stack trace. Mission accomplished.
The method call was not shown in the trace because the JIT optimizer inlined the method: this is the only way to hide methods in the stack trace.
It is not something you can control well, the method has to be 'small' and not throw any exception itself. This is otherwise normally considered a problem, not a feature. Hard to figure out how to code got from A to B.
您可以使用 DebuggerHiddenAttribute
You can use the DebuggerHiddenAttribute
如果您的方法不够简单而无法自动内联,您可以向编译器强烈提示您希望它使用
[MethodImpl(MethodImplOptions.AggressiveInlined)]
属性。您仍然必须在发布模式下编译。
If your method isn't simple enough to get inlined automatically, you can give the compiler a strong hint that you want it to be with the
[MethodImpl(MethodImplOptions.AggressiveInlining)]
attribute.You still have to compile in release mode.