3

I am wondering what is the best way to monitor a variable in C#. This is not for debugging. I basically want the program it self to monitor one of its variable all the time during running. For example. I am trying to watch if _a is less then 0; if it is, then the program stops.

 _a = _b - _c; // (_b >= _c) 

So _a ranges within [0 N], where N is some positive int; I feel the best is to start a thread that monitors the _a value. Once it, then I should response. But I have no idea how to implement it. Any one has any suggestions? A short piece of code sample will be highly appreciated.

Nick Tsui
  • 524
  • 2
  • 9
  • 29
  • Any reason the program should stop once it's below 0? Could it be solved by using unsigned int? – Tim Feb 26 '13 at 19:31
  • If you want just to debug some bugs in your program then have a look at this question: http://stackoverflow.com/questions/160045/visual-studio-debugger-break-when-a-value-changes – Eduard Dumitru Feb 26 '13 at 19:33
  • No I am not trying to debug. Trying to monitor the variable during the running program. I will edit my original post to make it clear. – Nick Tsui Feb 26 '13 at 19:38

3 Answers3

5

Instead of trying to monitor the value within this variable, you can make this "variable" a property of your class, or even wrap it's access into a method for setting the value.

By using a property or method, you can inject custom logic into the property setter, which can do anything, including "stopping the program."

Personally, if the goal was to stop the program, I would use a method:

private int _a;
public void SetA(int value)
{
    if (value < 0)
    { 
        // Stop program?
     }
    _a = value;
}

Then call via:

yourClass.SetA(_b - _c);

The reason I would prefer a method is that this has a distinct, dramatic side effect, and the expectation is that a property setter will be a quick operation. However, a property setter would work just as well from a technical standpoint.

A property could do the same thing:

private int _a;
public int A
{
    get { return _a; }
    set
    {
        if (value < 0)
        {
            // Handle as needed
        }

        _a = value;
    }
}
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

The best way is to encapsulate your variable with a property.

Using this approach you can extend the setter of your property with custom logic to validate the value, logging of changes of your variable or notification (event) that your variable/property has changed.

 private int _a;

 public int MyA {
  get{
    return _a;
  }
  set {
    _a = value;
  }
 }
Jehof
  • 34,674
  • 10
  • 123
  • 155
0

You should look into the Observer Pattern.

See Observer in .NET 4.0 with IObserver(T) and Understanding and Implementing Observer Pattern in C#.

Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92