【问题标题】:Issue with DispatcherTimer for a Countdown clock倒计时时钟的 DispatcherTimer 问题
【发布时间】:2015-05-05 16:00:21
【问题描述】:

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

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

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

然后,如果用户正确,我会使用按钮单击:

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

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

private void QuestionGenerator()
{
    CountDownTimer();

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

【问题讨论】:

    标签: c# windows-store-apps


    【解决方案1】:

    不要在每次拨打CountDown时订阅DispatcherTimer

    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 for Windows 8 Applications 进行更多研究。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多