代码之家  ›  专栏  ›  技术社区  ›  Rob Parker

NET源代码是否可以硬编码调试断点?

  •  66
  • Rob Parker  · 技术社区  · 16 年前

    我正在.NET(2.0,特别是C#)中寻找一种方法,让源代码触发调试中断,就像在该点设置了断点一样,而不必记住在调试器中设置特定的断点,也不会干扰生产运行时。

    我们的代码需要在生产中消化异常,这样我们就不会中断链接到我们的客户端应用程序,但我正在尝试对其进行设置,以便在调试器中运行时能够弹出此类错误进行分析,否则将被安全地忽略。

    Debug.Assert(false) 一直不太理想,我想 Debug.Fail()

    我希望像这样的事情 Debug.Break() ,但它似乎不存在(除非在.NET的更高版本中?),而且没有其他版本 Debug 方法似乎也适用。

    虽然ctacke的答案与我所寻找的最匹配,但我也发现了Debug.Assert()的一个技巧——在调试器中运行时——暂停调试器,转到Debug.Assert调用挂起的代码(在框架代码中以绿色突出显示,因为它位于下方)并点击跳出(shift-F11),然后在“断言”对话框中单击“忽略”。这将使调试器在返回断言时暂停(并且能够继续执行,就好像它没有发生一样,因为它被忽略了)。也许还有其他方法可以做同样的事情(点击重试是否更直接?),但这种方法是直观的。

    7 回复  |  直到 9 年前
        1
  •  134
  •   ctacke    6 年前

    你可能想要这样的东西:

    if(System.Diagnostics.Debugger.IsAttached)
      System.Diagnostics.Debugger.Break();
    

        // Conditional("Debug") means that calls to DebugBreak will only be
        // compiled when Debug is defined. DebugBreak will still be compiled
        // even in release mode, but the #if eliminates the code within it.
        // DebuggerHidden is so that, when the break happens, the call stack
        // is at the caller rather than inside of DebugBreak.
        [DebuggerHidden]
        [Conditional("DEBUG")] 
        void DebugBreak()
        {
            if(System.Diagnostics.Debugger.IsAttached)
                System.Diagnostics.Debugger.Break();
        }
    

    然后在代码中添加对它的调用。

        2
  •  12
  •   Kenny Evitt    6 年前

    System.Diagnostics.Debugger.Break ?

        3
  •  11
  •   CheGueVerra    16 年前

    我曾经遇到过这样一种情况,那就是这不起作用

    System.Diagnostics.Debugger.Break();
    

    System.Diagnostics.Debugger.Launch();
    
        4
  •  10
  •   Serg    6 年前

    #if DEBUG
           if (Debugger.IsAttached)
                Debugger.Break();
    #endif
    

    进入

    public static class DebugHelper
    {
        [DebuggerHidden]
        [Conditional("DEBUG")]
        public static void Stop()
        {
           if (Debugger.IsAttached)
                Debugger.Break();
        }
    }
    

    和使用

    DebugHelper.Stop();
    

    DebuggerHiddenAttribute Stop 方法和从使用 F11 .

        5
  •  4
  •   Lasse V. Karlsen    16 年前

    将VisualStudio配置为即使吞下调试器也能弹出调试器,怎么样?

    • 转到调试->例外情况。。。
    • 找到正确的异常,如果是您自己的,则添加它

    这将在引发异常的位置停止Visual Studio,而不仅仅是在未处理异常的情况下。

    您可以查看更多信息 here

        6
  •  4
  •   Jonathan C Dickinson    16 年前

        7
  •  1
  •   Aren Cambre    13 年前

    在VisualStudio2010中,点击 重试 Debug.Assert