倒计时时钟的 DispatcherTimer 问题 [英] Issue with DispatcherTimer for a Countdown clock

查看:20
本文介绍了倒计时时钟的 DispatcherTimer 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始开发一个测验应用程序,每个问题都有 60 秒的倒计时.我搜索了其他问题,但找不到我的具体问题.显示第一个问题时,屏幕显示60",倒计时正常进行.但是,当生成第二个问题时(单击提交按钮后),计数器再次启动,但这次使用 2 秒间隔.然后当第三个问题在点击后生成时,它以 3 秒为间隔倒计时!然后我注意到计时器显示在每个问题中的启动时间减少了 1 秒.(例如问题 1 以 60 开头,问题 2 以 59 开头......)

I have started developing a quiz app that will have a 60 second count down for each question. I searched other issues but could not find my specific issue. When the first question is displayed the screen dsplays "60" and the countdown proceeds normally. However, when the second questions is generated (after a button click submit) the counter starts again, but this time uses 2 second intervals. Then when the third question generates after a click, it counts down in 3 second intervals! I then noticed that the timer display starts 1 second less in each question. (ex Question 1 starts with 60, Question 2 starts with 59......)

这是我第一次使用 DispatcherTimer,所以我正在学习.我的目标是让计时器始终以 1 秒为间隔倒计时.

This is my first time using DispatcherTimer so I'm learning as I go. My goal is for the timer to always countdown in 1 second intervals.

public sealed partial class QuickPage : Page
{
    DispatcherTimer timeLeft = new Dispatcher();
    int timesTicked = 60;

    public void CountDown()
    {
        timeLeft.Tick += timeLeft_Tick;
        timeLeft.Interval = new TimeSpan(0,0,0,1);
        timeLeft.Start();
    }

    public void timeLeft_Tick(object sender, object e)
    {
        lblTime.Text = timesTicked.ToString();

        if (timesTicked > 0)
        {
            timesTicked--;
        }
        else
        {
            timeLeft.Stop();
            lblTime.Text = "Times Up";
        }
    }
}

然后我使用一个按钮单击如果用户是正确的:

I then use a button click where if th user is right:

timeLeft.Stop();
timesTicked = 60
QuestionGenerator();

问题生成器功能如下所示:

The Question Generator fucntion looks like this:

private void QuestionGenerator()
{
    CountDownTimer();

    if (iAsked < 6)
    {
        //Code to generate random question
    }
}

推荐答案

不要在每次调用 CountDown 时订阅 DispatcherTimer.

Do not subscribe to the DispatcherTimer every time you call CountDown.

DispatcherTimer timeLeft;
int timesTicked = 60;

public QuickPage()
{
    timeLeft = new Dispatcher();
    timeLeft.Tick += timeLeft_Tick;
    timeLeft.Interval = new TimeSpan(0,0,0,1);
}

private void QuestionGenerator()
{
    timeLeft.Start();

    if (iAsked < 6)
    {
        //Code to generate random question
    }
}

这篇关于倒计时时钟的 DispatcherTimer 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆