Problem with Debugger.Break();

While writing my previous post on how to debug live writer plugins, I mentioned using System.Diagnostics.Debugger.Break();  However, I found a problem with this. If you have a debugger attached, for example Visual Studio, then the program will hit the line of code and the debugger will step in. Great!

However, if no debugger is attached, the following error occurs:


I instantly thought this was strange, so built it as a Release version. Same thing happened. I know that with Debug.Write() the calls are removed in Release mode to save time, space and so no strange errors like this occurs.

First thing I did was boot up Reflector.  The debug class uses the ConditionalAttribute which provides a way to include/exclude methods depending on the preprocessor symbol.  So, if the Conditional compilation symbol is set to DEBUG then the method is included in the build, otherwise all the calls are removed.


However, if we look at Debugger.Break(), it doesn’t use a ConditionalAttribute which means we cannot take advantage of this compiler feature.  The result of this is that you need to manually remove all the lines of code which calls Debugger.Break() before shipping the code to the client, or when not running it with a debugger attached (like running unit tests). Not great at all!!

Strange how this got missed, unless it was done for a reason?? 

Technorati tags: , ,

One thought on “Problem with Debugger.Break();”

  1. Hi Ben,

    You can use conditional compilation in your code so that the method call is only invoked in a DEBUG build:

    #if DEBUG

    If you’d prefer you can use ConditionalAttribute instead:

    private void Break()

    and then just call your local Break method instead of Debugger.Break.

    It’s strange though how you’re not seeing a “Debug” button on the error dialog because in my experience using Debugger.Break() outside of VS I had the option of either “Debug” or “Continue”, IIRC. It’s been several months since I needed to use it though so I could be wrong…

    Anyway, I just wanted to say thanks for the posts about Live Writer. I had never heard of it before reading your posts and I’m very impressed with it. I’ve set it up for my blog but I just haven’t been able to sit down and use it yet…

    – Dave

Leave a Reply

Your email address will not be published. Required fields are marked *