Issue with DispatcherTimer for a Countdown clock

为君一笑 提交于 2019-12-13 03:47:52

问题


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......)

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
    }
}

回答1:


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
    }
}


来源:https://stackoverflow.com/questions/28858277/issue-with-dispatchertimer-for-a-countdown-clock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!