Debugging more efficiently

This is one of those gems that I read about quite a while ago but never used. Especially when working with multiple threads this technique is almost indispensable. How I ever made it before I don’t know.

If you’ve ever debugged your app (and I hope you have), there are few things more irritating than stepping through it and getting stuck in timer events that you don’t care about.

Another example is if you are building anything with network communication. Throw in a few socket events and while a breakpoint will get you where you want to start, the chances of stepping past the breaking function and not landing into a socket event are slim.

Finally, I’m not sure if it’s just differing IDE settings, but the F-keys for stepping through vs over seem to vary on my dev machines. Hitting the wrong one when you get to a function that loops internally 100,000 times, is just annoying.

The cheap solution is to set breakpoints at the beginning of the functions you care about, and just F5 whenever you hit one of the aforementioned events, or in the case of the last example, you would have to set a breakpoint either after the loop or at the next line in the calling function.

Today I was reminded of a MUCH easier way to debug efficiently. I had intended to post a link to the MSDN page for the attribute that performs this wizardry, but such a thing does not exist. Even in the VS help (which is pretty much just MSDN anyhow) there is no mention of it. There is a similarly named class, but this voodoo attribute apparently does not officially exist. In order to use the attribute, you must add a using clause for System.Diagnostics.

Alright, I’ll tell you, all it takes, is one line above the method/function, property accessor, struct or class that you do not want to step through. That line is

[DebuggerStepThrough]

Yep, that’s it. As far as the Framework is concerned, this is a meaningless attribute and serves a purpose only in Visual Studio. It will also not appear in the Intellisense list. I have not tested it with Sharp Develop. For methods, structs and classes, just add that tag above the first line and you’re good to go. For properties, you would place it immediately before the get or set lines.

One thing to remember, is the debugger will pass over any breakpoints that are in the chunk of code the tag applies to. I personally find it easier to just comment the line when I have a need to debug one of the tagged blocks of code. But there is also an option in the IDE. If you go to Tools > Options > Debugging > General (VS2005), and remove the check from Enable Just My Code (Managed only), then the attribute can stay, and breakpoints within the affected blocks will break as expected.