Timer cannot be stopped in C#

六月ゝ 毕业季﹏ 提交于 2019-12-13 02:58:28

问题


I have a timer on a windows form (C# 3.0, .net 3.5 SP1, VS2008 SP1, Vista) that seems to work even after it is stoppped. The code is:

using System;
using System.Windows.Forms;

namespace TestTimer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            StartTimer();
        }

        private DateTime deadline;

        private void StartTimer()
        {
            deadline = DateTime.Now.AddSeconds(4);
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int secondsRemaining = (deadline - DateTime.Now).Seconds;

            if (secondsRemaining <= 0)
            {
                timer1.Stop();
                timer1.Enabled = false;
                MessageBox.Show("too slow...");
            }
            else
            {
                label1.Text = "Remaining: " + secondsRemaining.ToString() + (secondsRemaining > 1 ? " seconds" : " second");
            }
        }
    }
}

Even after the timer1.Stop() is called, I keep reeciving MessageBoxes on the screen. When I press esc, it stops. Howevere, I've expected that only one message box appears... What else should I do? adding timer1.Enabled = false does not change the behavior.

Thanks


回答1:


I could be wrong, but is MessageBox.Show() a blocking operation (that waits for you to dismiss the dialog)? If so, just move the Show() call to after the Stop/Enabled lines?




回答2:


A couple of factors may be at work here.

The modal MessageBox.Show() could prevent the timer stop from taking effect until it is dismissed (as Brian pointed out).

The timer1_Tick could be executing on a background thread. UI calls such as MessageBox.Show() and background threads to not mix.

Both issues can be solved by using BeginInvoke to call a method that shows the message box.




回答3:


Note that the following is unnecessary:

            timer1.Stop();
            timer1.Enabled = false;

Stop() is the same as Enabled=false. And Start() is the same as Enabled=true.

http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.enabled.aspx



来源:https://stackoverflow.com/questions/590141/timer-cannot-be-stopped-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!