簡體   English   中英

如果設置C#計時器會過快

[英]c# timer is going too fast if set

我正在嘗試使用Timer(使用https://www.geoffstratton.com/cnet-countdown-timer代碼)實現簡單的倒計時。 如果我運行一次計時器,它確實可以工作,但是如果我停止計時器,或者下一次我將其啟動到00:00時,它將快2倍。 如果我停止並重新啟動它,它的運行速度將提高3倍。

(我的解釋可能不清楚,我做了一個gif來演示問題) https://media.giphy.com/media/fQr7sX6LNRECvQpCYP/giphy.gif

我是C#的新手,我通常會想辦法,但我無法了解這里發生的情況。 我包括了計時器代碼。 如果有人可以幫助我,那就太好了! 謝謝 !!!

        private void btnStartTimer_Click(object sender, EventArgs e)
    {
        if (txtTimer.Text == "00:00")
        {
            MessageBox.Show("Please enter the time to start!", "Enter the Time", MessageBoxButtons.OK);
        }
        else
        {
            string[] totalSeconds = txtTimer.Text.Split(':');
            int minutes = Convert.ToInt32(totalSeconds[0]);
            int seconds = Convert.ToInt32(totalSeconds[1]);
            timeLeft = (minutes * 60) + seconds;
            btnStartTimer.Enabled = false;
            btnCleartimer.Enabled = false;
            txtTimer.ReadOnly = true;
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Start();
        }
    }
    private void btnStopTimer_Click(object sender, EventArgs e)
    {
        timer1.Stop();
        timeLeft = 0;
        btnStartTimer.Enabled = true;
        btnCleartimer.Enabled = true;
        txtTimer.ReadOnly = false;
    }
    private void btnCleartimer_Click(object sender, EventArgs e)
    {
        txtTimer.Text = "00:00";
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
        if (timeLeft > 0)
        {
            timeLeft = timeLeft - 1;
            // Display time remaining as mm:ss
            var timespan = TimeSpan.FromSeconds(timeLeft);
            txtTimer.Text = timespan.ToString(@"mm\:ss");
            // Alternate method
            //int secondsLeft = timeLeft % 60;
            //int minutesLeft = timeLeft / 60;
        }
        else
        {
            timer1.Stop();
            SystemSounds.Exclamation.Play();
            MessageBox.Show("Time's up!", "Time has elapsed", MessageBoxButtons.OK);
        }
    }

您需要通過btnStopTimer_Click方法退訂該事件:

timer1.Tick -= timer1_Tick;

每次啟動計時器時,您都將事件添加到Count中。 結果,第一次調用時只有一個事件,第二次只有兩個事件,依此類推。 結果,您首先需要等待一秒鍾,然后再等待兩個.....我建議您分別創建計時器,然后僅調用Start和Stop。 Alternativ,如果您不想在其他地方創建計時器,則用戶Dmitry Korolev回答了一個不錯的方法

timer1.Tick -= timer1_Tick;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM