Can .NET source code hard-code a debugging breakpoint?

此生再无相见时 提交于 2019-11-29 20:22:52

You probably are after something like this:

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

Of course that will still get compiled in a Release build. If you want it to behave more like the Debug object where the code simply doesn't exist in a Release build, then you could do something like this:

    // 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();
    }

Then add a call to it in your code.

shahkalpesh

System.Diagnostics.Debugger.Break?

If you want to have only one line of code instead of 4, wrap

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

into

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

and use

DebugHelper.Stop();

DebuggerHiddenAttribute has been added to prevent the debugger from stopping on the inner code of the Stop method and from stepping into the method with F11.

I ran into a situation once where this didn't work

System.Diagnostics.Debugger.Break();

but this did

System.Diagnostics.Debugger.Launch();

How about just configuring Visual Studio to pop up with the debugger even if you swallow it?

Do this:

  • Go to Debug->Exceptions...
  • Find the right exception, or add it if it's your own
  • Check the "Thrown" checkbox for the exception

This will stop Visual Studio on the location that exception is thrown, not just if it isn't handled.

You can see more information here.

A nice trick I found is putting Debugger.Break() in the ctor of your Exception.

In Visual Studio 2010, hitting Retry on a Debug.Assert dialog takes you to the failed debug assertion, just as if you had a breakpoint.

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