Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pause execution when a watch variable changes?

Is it possible to break execution when a watch variable (not a property, just a normal variable) changes to see where the change occurred? I searched and found this question which relates to properties it seems which is not what I'm looking for.

This variable is used several times in several thousand lines of code, but it is only changed from null when a problem happens. We are trying to track that problem down.

like image 801
ldam Avatar asked Feb 14 '13 11:02

ldam


People also ask

Which window should you use to cause VBA execution to pause when the value of a variable changes?

You can display the Watch window by choosing Watch Window from the View menu. A Watch is an instruction to VBA to pause code when an expression is True or when the variable being watched changes value.

How do you break a variable change in Visual Studio?

Setting a data breakpoint is as easy as right-clicking on the property you're interested in watching inside the watch, autos, or locals window and selecting “Break when value changes” in the context menu. All data breakpoints are displayed in the Breakpoints window.

What are watch variables?

Any item of data within a program that a programmer wants to observe when debugging. Watch variables may be viewed while the program runs on its own, is stepped through instruction by instruction or when the program crashes. Setting watch variables is part of the debugging operation in a compiler.

How do I pause a run in Visual Studio?

Select the left margin or press F9 next to the line of code you would like to stop at. Run your code or hit Continue (F5) and your program will pause prior to execution at the location you marked.


1 Answers

  1. Create a breakpoint (f9) around the variable
  2. Right-click on the red circle of the breakpoint and click on "Condition..."
  3. Type in the name of the variable, and change the radio to "Has changed"
  4. The breakpoint should now have a + in it to indicate that it is conditional

However: frankly, I find the following simpler and much more efficient - especially for fields; say we start with:

string name;

we change it just for now to:

private string __name;
string name {
    get { return __name; }
    set { __name = value; }
}

and just put a break-point on the set line. It should still compile, and you can see the change trivially. For more complex cases:

private string __name;
string name {
    get { return __name; }
    set {
        if(__name != value) {
            __name = value; // a non-trivial change
        }
    }
}

and put the breakpoint on the inner-most line; this bypasses code that sets the field without actually changing the value.

like image 97
Marc Gravell Avatar answered Sep 29 '22 20:09

Marc Gravell