Programatically Breaking Into the Debugger

An entry about visual studio Publication date 4. May 2007 16:31

Lately I've been exploring the System.Diagnostics namespace (previously I've posted about how to get the current stack trace), and one class that I've discovered which is pretty cool is the Debugger class. Essentially, it allows you to communicate with any debugger that is currently attached to the process. Apart form letting you send log messages to the debugger, it allows you to signal a breakpoint aswell - basically you can say:

Debugger.Break();

anywhere in your code, and the debbuger will act as if there was a breakpoint on that line of code, making the application break into it. That's pretty cool - but what's even cooler, is that if no debugger is attached, you will get the following prompt:

Breakpoint prompt

Hit debug, and you will be able to attach a debugger and then break into the code. Now you might not want to do this in production code - so you should probably wrap the Debugger.Break() call in a method decorated with the Conditional attribute and the condition "DEBUG" (which I consider a better practice than #if DEBUG), which will ensure that it wont get called if you're running a release build:

[Conditional("DEBUG")]
public static void BreakIntoDebugger()
{
Debugger.Break();  
}

Currently rated 1.0 by 1 people

  • Currently 1/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.

NDC 2010

The conference to attend this summer happens June 16th-18th in Oslo, Norway. Are you going? Be sure to catch my talk on AOP while you're there!

 

Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS