简体   繁体   中英

Timer ticks with wrong values

I am developing a game in Windows Phone 8 SDK and i need a countdown timer.

i implemented a Dispatcher timer , on the first time CLICK The timer decrease with no errors !

but if i press RESET (Which it should reset to 60 SECONDS and start countdown) it Resets to 60 BUT it Decreases " 2 Seconds " every second !

and if i press one more time RESET , it Decreases by 3 Seconds every second

Sample code i wrote with the same idea of my app: (and same wrong results)

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 
        }


    }
}

Every time you press reset, and Start_Click_1 runs again, you're subscribing to time_Tick again:

time.Tick += time_Tick;

So after pressing Reset 3 times, you're subscribed 3 times, and the following line of code is running 3 times every time the tick event fires:

left--;

Move the subscription to your constructor:

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();
}

As Hans said in the comments, you are incorrectly adding the event handler every time the button is clicked.

You should call this code

time.Interval = TimeSpan.FromSeconds(1);
time.Tick += time_Tick;

in the constructor, instead of the event handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM