【问题标题】:How to disable exceptions stack trace gathering in .NET CLR while executing specific methods?如何在执行特定方法时禁用 .NET CLR 中的异常堆栈跟踪收集?
【发布时间】:2014-09-29 00:11:06
【问题描述】:

我有一个每秒被调用超过 100 次的方法,由于它的内部实现,它经常抛出异常。

由于方法的内部实现,无法阻止这些异常,但我想降低这些异常的性能成本,例如通过禁用异常的堆栈跟踪收集,因为这些信息对我来说并不方便。

有什么想法吗?

方法实现:

 public static TValue GetValue<TObj, TValue>(this TObj obj, Func<TObj, TValue> member, TValue defaultValueOnNull = default(TValue))
    {
        if (member == null)
            throw new ArgumentNullException("member");

        if (obj == null)
            throw new ArgumentNullException("obj");

        try
        {
            return member(obj); // We've lots of null reference exceptions here.
// And I'm not interested in stack trace of those exceptions, how to reduce performance costs here ?
            }
            catch (NullReferenceException)
            {
                return defaultValueOnNull;
            }
        } 

方法用法:

String flightNumber = originDestinationInformation.GetValue(dest => dest.OriginDestinationOption.FlighInfo.FlightNumber, "");

【问题讨论】:

  • NullReferenceException 是您必须防止不捕获的东西。
  • 如果有一些神奇的标志来做到这一点,系统将仍然必须一直向上遍历各种堆栈帧,执行展开等,直到 找到那个神奇的旗帜。它不会在性能方面节省太多。
  • @SriramSakthivel 是的,你说得对,但我已经使用这种方法来获得更清晰的代码,而无需对对象进行大量“如果非空”检查。
  • @YasserMoradi 很抱歉这么说:您的评论很荒谬。如果您不想检查空使用NullObject Pattern,则不应捕获NullReferenceException。恕我直言,捕获NullReferenceException 的代码是废话。
  • 那你为什么有if (member == null)if (obj == null) 支票呢?您可以消除它并获得更好的代码,不是吗?

标签: c# .net performance exception-handling clr


【解决方案1】:

AFAIK,如果不修改 .NET 框架,您将无法做到这一点。

【讨论】:

  • 对该问题的第一个相关答案/评论。我认为我的要求没有解决方案。
猜你喜欢
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 2012-08-22
  • 2011-03-16
  • 2011-02-27
  • 2011-01-05
  • 2017-08-06
  • 2010-09-13
相关资源
最近更新 更多