spa*_*opt 3 c# multithreading timer intervals windows-phone-8
我在 Windows Phone 8 项目中有以下计时器:
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();
}
Run Code Online (Sandbox Code Playgroud)
我的第一个问题是:可以在到达下一个滴答之前停止计时器吗?或者换句话说,可以立即停止计时器吗?
第二个问题:我想改变间隔。我是否需要停止并重新启动才能识别新的时间间隔?我看到有一个 interval 属性,但它不允许我设置值,只能获取它。
答案 1:
是的,可以timer立即停止。你可以通过调用它的Stop()方法来停止它:
dt.Stop();
Run Code Online (Sandbox Code Playgroud)
答案 2:
不,你并不需要Stop在timer改变它的interval。这是你如何设置新的interval(你已经做了同样的事情):
dt.Interval = new TimeSpan(0, 0, 1); // one second
Run Code Online (Sandbox Code Playgroud)
当您设置 时interval,它不会自行重新启动,它只是跟随新的interval.
详情可以查看以下链接: DispatcheTimer
更新:
根据您的代码停止timer:
private void turnoff(){ dt.stop();}
Run Code Online (Sandbox Code Playgroud)
不起作用。因为你timer在另一个方法中,所以在那个方法之外它的范围已经完成,你不能在另一个方法中调用它。为此,您必须使全局,如下所示:
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5994 次 |
| 最近记录: |