ldam
ldam

Reputation: 4585

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.

Upvotes: 9

Views: 17805

Answers (2)

Chenzhuo
Chenzhuo

Reputation: 1

inside vs code:

  1. right click on breakpoint, choose EditBreakpoint right click, edit breakpoint

  2. in the Expression, enter an expression as condition, when to stop the program e.g. SomeVariable == 0x7f2c44a31f98 (0x7f2c44a31f98 is the address of the variable to be watched) enter an expression for break condition

  3. press enter

For our example, when SomeVariable is equal to 0x87654321, it won't stop, once the SomeVariable is equal to 0x7f2c44a31f98, it will stop

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062780

  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.

Upvotes: 6

Related Questions