Kavitha
Kavitha

Reputation: 69

Timer continuously firing in C#, Not able to stop

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

Upvotes: 0

Views: 1364

Answers (3)

lukas
lukas

Reputation: 349

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.

Upvotes: 0

Darren
Darren

Reputation: 70786

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
   }

Upvotes: 2

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

You are incrementing count1 and checking count.

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

Upvotes: 0

Related Questions