2012-07-11 116 views
0

如何暂停WP7中的定时器? 在我的应用程序中,我想暂停并恢复计时器。但是DispatcherTimer只能启动和停止。如何暂停计时器?如何暂停DispatchTimer?

回答

0

尝试将IsEnabled属性设置为false以停止它,然后在您希望继续时返回true。

0

对于暂停/恢复功能,您必须将其构建到您的Tick处理程序中,启动和停止计时器。

如果你的计时器的时间间隔约为60秒钟,然后试试这个:

dispatcher_Timer.Interval = TimeSpan.Fromseconds(30); 

dispatcher_Timer.Tick += new EventHandler(dispatcherTimer_Tickon); 

dispatcher_Timer.Start(); 

private void dispatcherTimer_Tickon(object sender, EventArgs e) 
{ 
    dispatcher_Timer.Tick -= new EventHandler(dispatcherTimer_Tickon); 
    // Do the work for 30 seconds and pause it using stop    
    dispatcher_Timer.Stop(); 

    dispatcher_Timer.Tick += new EventHandler(dispatcherTimer2_Tickon); 
    dispatcher_Timer.Start(); 
} 

private void dispatcherTimer2_Tickon(object sender, EventArgs e) 
{ 
    dispatcher_Timer.Tick -= new EventHandler(dispatcherTimer2_Tickon); 
    // Do the remaining work for 30 seconds and pause it using stop    
    dispatcher_Timer.Stop(); 
} 
0

没有办法暂停计时器,后来有它继续离开的地方。启用简单的 调用启动和停止。

您需要创建自己的计时器才能拥有此功能。

+0

我不认为这样做,根据http://stackoverflow.com/questions/3163300/what-is-the-different-between-isenabled-and-start-stop-of-dispatchertimer – 2012-07-11 08:28:44

+1

我不要以为他在这个职位上是正确的。如果您查看DispatchTimer的源代码,则isEnabled只会调用Start和Stop。 – Jon 2012-07-11 09:28:53

+0

谢谢你清理! :) – 2012-07-11 09:43:08

1

试试这个: 定义一个全局变量:

private static DateTime EndTime { get; set; } 

然后,当按下启动按钮,您进行以下检查以确定计时器是否已经停止或暂停:

private void btnStartClick(object sender, RoutedEventArgs e) 
{ 
    if (this.dispatcherTimer == null) 
    { 
     this.dispatcherTimer = new DispatcherTimer(); 
     this.dispatcherTimer.Interval = TimeSpan.FromMilliseconds(100); 
     this.dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick); 
    } 

    if (this.EndTime == DateTime.MinValue) 
    { 
     this.EndTime = DateTime.Now + (TimeSpan)this.timeSpan.Value; 
    } 

    this.dispatcherTimer.Start(); 
} 

接下来,当按下暂停按钮时,您可以停止定时器,因为下次按下开始按钮时,您将通过上述检查:

private void btnPauseClick(object sender, RoutedEventArgs e) 
{ 
    this.dispatcherTimer.Stop(); 
}