I have an event inside my program in which there are values of tantheta keeps on changing on subsequent events fires.
The problem is that I have to check whether this value of tantheta holds within a certain range of 0.6 to 1.5 for a period of 3 seconds.
I tried some things with the timer but didn’t work out. Any suggestions?
EDIT–
DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
//This event is fired automatically 32 times per second.
private void SomeEvemt(object sender, RoutedEventArgs e)
{
tantheta = ; tantheta gets a new value here through some calculation
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
//if condition to check if tantheta is within range and do something
}
void timer_Tick(object sender, EventArgs e)
{
DispatcherTimer thisTimer = (DispatcherTimer)sender;
textBox1.Text = thisTimer.Interval.ToString();
thisTimer.Stop();
return;
}
I have to check if tantheta value remains within 0.6 to 1. for three seconds. I though timer would be a good approach since it would prevent my application from freezing during all these calculations because it goes to a separate thread. :-/
A timer is useless because you will poll too many times and miss out on a change/change back.
You will have to encapsulate the setting of the variable.
This way you can respond to changes of the variable.
Now all you have to do is subscribe to the TanThetaWentOutOfBounds event of this class and set the CheckBoundaries to true or false.
Note that this code does not fix any multi threading issues so you might have to add some locking depending on your use of the class.
There are two way to handle the 3 second periods:
In the TanThetaWentOutOfBounds handler (some other class that registers for the event) keep track of the time of the previous update and only take action when the event is raised within 3 second from the start of measuring. This way the responsibility of implementing the period is given to the consumer.
You could decide to raise the event only if less then 3 seconds have passed since the previous time the event was raised. This way you restrict all the consumers to the period you are implementing in the raiser. Note that I used DateTime.Now to get the time, this is not as accurate as the Stopwatch class.
Code: