如何暂停DispatcherTimer?

时间:2012-07-11 07:19:25

标签: windows-phone-7

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

5 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

对于Pause / Resume功能,您必须将其构建到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();
}

答案 3 :(得分:0)

没有办法暂停计时器,之后让它继续停止。 IsEnabled简单 调用开始和停止。

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

答案 4 :(得分:0)

您可以通过这个简单的技巧轻松暂停 Dispatcher,如果您将时间间隔设置为零会怎样?

这将暂停调度程序

 dispatcherTimer.Interval.Subtract(dispatcherTimer.Interval); 

再次恢复 dispatchTimer 只需将时间跨度添加到 Interval。

dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 5); // this will

dispatcherTimer.Interval = TimeSpan.FromMilliseconds(100);