持续监控一个变量而不是无限循环,然后在它发生变化时做一些事情
Continuously monitor a variable without infinite loop, then do something when it changes
我不太确定如何扩展我的问题,但是您如何连续监视一个变量(没有无限 loop/in-UI 计时器),然后在它发生变化时采取措施?我正在考虑使用一个事件,但我还不是很擅长。我正在考虑 System.Threading.Timer,但有其他选择会更好。
我正在使用 .NET 4.0,并将制作一个 Windows 表单。
EDIT:您可以通过输入或编程方式修改变量。它可以是任何变量:整数、字符串、布尔值等
您应该使用 INotifyPropertyChanged 以便在变量更改时收到通知。
这里有一个更简单的解决方案:
好吧,它实际上并没有监视您的变量,但它会告诉您变量何时发生变化。
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;
}
}
当你想获取或设置一个新值时,取 Variable
-> 不要给 variable
赋值
我不太确定如何扩展我的问题,但是您如何连续监视一个变量(没有无限 loop/in-UI 计时器),然后在它发生变化时采取措施?我正在考虑使用一个事件,但我还不是很擅长。我正在考虑 System.Threading.Timer,但有其他选择会更好。
我正在使用 .NET 4.0,并将制作一个 Windows 表单。
EDIT:您可以通过输入或编程方式修改变量。它可以是任何变量:整数、字符串、布尔值等
您应该使用 INotifyPropertyChanged 以便在变量更改时收到通知。
这里有一个更简单的解决方案:
好吧,它实际上并没有监视您的变量,但它会告诉您变量何时发生变化。
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;
}
}
当你想获取或设置一个新值时,取 Variable
-> 不要给 variable