Timer continuously firing in C#, Not able to stop

﹥>﹥吖頭↗ 提交于 2019-12-25 01:35:13

问题


Could any one help me to stop my timer in windows form C3 application? I added timer in form using designer and interval is set as 1000; I would like to do some actions after 5 seconds of waiting after button click. Please check the code and advise me. Problem now is I get MessageBox2 infinitely and never gets the timer stop.

static int count;

public Form1()
        {
            InitializeComponent(); 
            timer1.Tick += timer1_Tick;
        }
public void button1_Click(object sender, EventArgs e)
        {

        timer1.Enabled = true;

        while(count>5)
         {
          ....dosome actions...
         }

        }
private void timer1_Tick(object sender, EventArgs e)
        {
            count1++;
           MessageBox.Show("Messagebox2");
           if (count1 == 5)
           {
               //timer1.Enabled = false; timer1.Stop(); 
               ((System.Timers.Timer)sender).Enabled = false;
               MessageBox.Show("stopping timer");
           }
        }

回答1:


I would render the count useless and just use the timer 1 interval property and put your actions in the timer1_Tick event.

  public void button1_Click(object sender, EventArgs e)
    {
          timer1.Interval = 5000;
          timer1.Enabled = true;
    }

   private void timer1_Tick(object sender, EventArgs e)
   {
        timer1.Enabled = false;  
        MessageBox.Show("stopping timer");
        // Your other actions here
   }



回答2:


You are incrementing count1 and checking count.

while(count1 > 5)
{
    ...dosome actions...
}



回答3:


Which Timer do you use? Because C# supports class Timer from two different namespaces. One is from Forms, the other is from System.Timers. I would suggest you to use the other one - System.Timers.Timer.

                Timer t = new Timer(20000); // created with 20seconds
            t.Enabled = true; // enables firing Elapsed event
            t.Elapsed += (s, e) => {
                \\do stuff
            };

            t.Start();

In this short code you can see how the timer is created and enabled. By registering to the Elapsed event you explicitly say what to do after the time elapses. and this is done just once. Of course, there are some changes needed in case user clicks button before your limit is reached. But this is highly dependent on behavior of the action you demand.



来源:https://stackoverflow.com/questions/10961341/timer-continuously-firing-in-c-not-able-to-stop

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