计时器计时错误
本文关键字:错误 计时器 | 更新日期: 2023-09-27 17:49:18
我正在开发一款基于Windows Phone 8 SDK的游戏我还需要一个倒数计时器。
我实现了一个Dispatcher定时器,在第一次CLICK定时器减少,没有错误!
但是如果我按RESET(它应该重置为60秒并开始倒计时)它重置为60 但是每秒减少"2秒"
,如果我再按一次RESET,它每秒减少3秒
示例代码我写了与我的应用程序相同的想法:(和同样的错误结果)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp3.Resources;
using System.Windows.Threading;
namespace PhoneApp3
{
public partial class MainPage : PhoneApplicationPage
{
private DispatcherTimer time = new DispatcherTimer(); // DISPATCHER TIMER
private int left;
// Constructor
public MainPage()
{
InitializeComponent();
}
//Starting Countdown
private void Start_Click_1(object sender, RoutedEventArgs e)
{
left = 60; // time left
time.Interval = TimeSpan.FromSeconds(1);
time.Tick += time_Tick;
time.Start();
}
void time_Tick(object sender, EventArgs e)
{
left--; // decrease
txt.Text = Convert.ToString(left); // update text
}
private void reset_Click(object sender, RoutedEventArgs e)
{
time.Stop();
Start_Click_1(null, null); // RE - START
}
}
}
每次按复位键,Start_Click_1
再次运行,您将再次订阅time_Tick
:
time.Tick += time_Tick;
所以在按下Reset 3次之后,您订阅了3次,并且每次tick事件触发时,下面的代码行都会运行3次:
left--;
将订阅移动到构造函数:
public MainPage()
{
InitializeComponent();
time.Tick += time_Tick;
}
//Starting Countdown
private void Start_Click_1(object sender, RoutedEventArgs e)
{
left = 60; // time left
time.Interval = TimeSpan.FromSeconds(1);
time.Start();
}
正如Hans在评论中所说,每次单击按钮时都错误地添加事件处理程序。
你应该调用这个代码
time.Interval = TimeSpan.FromSeconds(1);
time.Tick += time_Tick;
,而不是事件处理程序。