Visual Studio Debugger Tips and Tricks: Tracepoints

Thursday, June 19, 2014

Mariusz Wojcik

This time I want to present you Tracepoints in Visual Studio debugger. Tracepoints are special kind of break points which allows you to specify an action to execute when hit. The most common case for trace point is to print some tracing message. Let’s look at the example. Below is the code that generates all possible combinations of numbers in given range1 and performs some processing on those:

Say, we are interested in seeing what combinations were generated. You could step through the loop or place break point there and observe variables but this will take time and give you only the current value. You could stop your debugging session, add some tracing code to the loop, and run debugging again, but this has many problems. You have to break your debugging session, make code changes, recompile and restore your debugging sessions. It’s OK on a small, test project, but what if compiling takes time. What if it takes time to reach the code you want to debug? What if you do not have access to Console – hopefully you are using some logging framework which could be used, but that means going through log files to dig out data you are interested in. And frankly – do you really want to add make temporary changes to the code? Risk that you forget to remove those and check them in?

Lets see how trace points can help. Instead of breaking debugging session, right click in the line no 6 and select Breakpoint > Insert Tracepoint from the menu:

This will show modal window like the one below:

You can specify message which will be printed in the Output window each time the trace point is hit. As you can see from the description you can print variables or other expressions, information about function, thread or call stack. For our test lets set the message to:

Also, leave Continue execution checked, as we do not want debugger to break.

Now, if we continue execution and let the whole loop to run, the list of all 20 combinations will be printed in the Output window2:

The Output window is searchable (click Ctrl+F to show search dialog). You can do Find All (click small down arrow next to Search Term text box and select Find All) to show all references in Find Results window. And if you want, you can save content of the Output window to a text file (Ctrl+S).