Aloha
Aloha

Reputation: 914

Continuously monitor a variable without infinite loop, then do something when it changes

I'm not quite sure how to expand my question, but how do you continuously monitor a variable (without an infinite loop/in-UI timer), then do something when it changes? I'm thinking about using an event but I'm not very good at it yet. I'm thinking about System.Threading.Timer but an alternative would be nice.

I'm using .NET 4.0, and will make a Windows Form.

EDIT: You can modify the variable, either from input or programatically. It can be any variable: integer, string, boolean, etc.

Upvotes: 2

Views: 1121

Answers (2)

Jibbow
Jibbow

Reputation: 757

Here is a more simple solution:

Well, it actually isn't monitoring your variable but it tells you when it has been changed.

 private string variable = "";//don't acces this variable: it's just for storing the value in it
 string Variable //this variable should be used by all your code
 {
     get { return variable; }
     set
     {
         if (value != variable)
         {
              //the variable has been changed
              //here is usually an event that is raised, but you could also write your code directly here for some simple cases

         }
         variable = value;
     }
}

When you want to get or set a new value, take Variable -> don't assign anything to variable

Upvotes: 1

user1230733
user1230733

Reputation:

You should use INotifyPropertyChanged in order to be notified whenever the variable is changed.

See more : https://msdn.microsoft.com/fr-fr/library/system.componentmodel.inotifypropertychanged%28v=vs.110%29.aspx

Upvotes: 0

Related Questions