倒计时时钟的 DispatcherTimer 问题
Issue with DispatcherTimer for a Countdown clock
我已经开始开发一个测验应用程序,每个问题都有 60 秒的倒计时。我搜索了其他问题,但找不到我的具体问题。当显示第一个问题时,屏幕显示“60”,倒计时正常进行。但是,当生成第二个问题时(单击提交按钮后),计数器再次启动,但这次使用 2 秒间隔。然后当第三个问题在点击后生成时,它会以 3 秒为间隔倒计时!然后我注意到每个问题的计时器显示开始时间都减少了 1 秒。 (ex问题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
}
}
每次调用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
}
}
我已经开始开发一个测验应用程序,每个问题都有 60 秒的倒计时。我搜索了其他问题,但找不到我的具体问题。当显示第一个问题时,屏幕显示“60”,倒计时正常进行。但是,当生成第二个问题时(单击提交按钮后),计数器再次启动,但这次使用 2 秒间隔。然后当第三个问题在点击后生成时,它会以 3 秒为间隔倒计时!然后我注意到每个问题的计时器显示开始时间都减少了 1 秒。 (ex问题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
}
}
每次调用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
}
}