Break when a value changes using the Visual Studio

2020-01-27 09:51发布

Is there a way to place a watch on variable and only have Visual Studio break when that value changes?

It would make it so much easier to find tricky state issues.

Can this be done?

Breakpoint conditions still need a breakpoint set, and I'd rather set a watch and let Visual Studio set the breakpoints at state changes.

13条回答
Anthone
2楼-- · 2020-01-27 10:30

You can also choose to break explicitly in code:

// Assuming C#
if (condition)
{
    System.Diagnostics.Debugger.Break();
}

From MSDN:

Debugger.Break: If no debugger is attached, users are asked if they want to attach a debugger. If yes, the debugger is started. If a debugger is attached, the debugger is signaled with a user breakpoint event, and the debugger suspends execution of the process just as if a debugger breakpoint had been hit.

This is only a fallback, though. Setting a conditional breakpoint in Visual Studio, as described in other comments, is a better choice.

查看更多
我只想做你的唯一
3楼-- · 2020-01-27 10:30

I remember the way you described it using Visual Basic 6.0. In Visual Studio, the only way I have found so far is by specifying a breakpoint condition.

查看更多
我命由我不由天
4楼-- · 2020-01-27 10:30

You can optionally overload the = operator for the variable and can put the breakpoint inside the overloaded function on specific condition.

查看更多
男人必须洒脱
5楼-- · 2020-01-27 10:34

Imagine you have a class called A with the following declaration.

class A  
{  
    public:  
        A();

    private:
        int m_value;
};

You want the program to stop when someone modifies the value of "m_value".

Go to the class definition and put a breakpoint in the constructor of A.

A::A()
{
    ... // set breakpoint here
}

Once we stopped the program:

Debug -> New Breakpoint -> New Data Breakpoint ...

Address: &(this->m_value)
Byte Count: 4 (Because int has 4 bytes)

Now, we can resume the program. The debugger will stop when the value is changed.

You can do the same with inherited classes or compound classes.

class B
{
   private:
       A m_a;
};

Address: &(this->m_a.m_value)

If you don't know the number of bytes of the variable you want to inspect, you can use the sizeof operator.

For example:

// to know the size of the word processor,  
// if you want to inspect a pointer.
int wordTam = sizeof (void* ); 

If you look at the "Call stack" you can see the function that changed the value of the variable.

查看更多
你好瞎i
6楼-- · 2020-01-27 10:34

Right click on the breakpoint works fine for me (though mostly I am using it for conditional breakpoints on specific variable values. Even breaking on expressions involving a thread name works which is very useful if you're trying to spot threading issues).

查看更多
仙女界的扛把子
7楼-- · 2020-01-27 10:37

You can probably make a clever use of the DebugBreak() function.

查看更多
登录 后发表回答