Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop and change interval of System.Window.Threading.DispatcherTimer

I have the following timer in a windows phone 8 project:

private void temperatureTimer()
{
    System.Windows.Threading.DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
    dt.Interval = new TimeSpan(0, 0, 1, 0, 0); 
    dt.Tick += new EventHandler(dt_Tick);
    dt.Start();
}

My first question is: it's possible to stop the timer before it reaches the next tick? Or by other words, it's possible to stop the timer instantly?

Second question: I want to change the interval. Do I need to stop it and start it again in order to recognize the new interval? I see there is a interval property but it doesn't let me set the value, only get it.

like image 925
sparcopt Avatar asked Sep 13 '25 20:09

sparcopt


1 Answers

Answer 1:

Yes it is possible to stop the timer immediately. You can stop it by calling its Stop() method:

dt.Stop();

Answer 2:

No you don't need to Stop the timer to change its interval. This is how you can set the new interval (you've already done the same):

dt.Interval = new TimeSpan(0, 0, 1); // one second

When you set the interval, it doesn't restart itself, it just follows the new interval.

You can see the following link for details: DispatcheTimer

Update:

According to your code to stop the timer:

private void turnoff(){ dt.stop();}

It will not work. Because your timer is in another method, so out of that method its scope has been finished, you can not call it in another method. To do this you will have to make global, like this:

System.Windows.Threading.DispatcherTimer dt; //declaration outside the method
private void temperatureTimer()
{
    dt = new System.Windows.Threading.DispatcherTimer(); //initialization inside a method
    dt.Interval = new TimeSpan(0, 0, 1, 0, 0); 
    dt.Tick += new EventHandler(dt_Tick);
    dt.Start();
}

private void turnoff() //now your this method will work to stop the timer
{ 
    dt.stop();
}
like image 118
Shaharyar Avatar answered Sep 15 '25 09:09

Shaharyar