Hoang Viet
Hoang Viet

Reputation: 346

How do Timers work in .net?

I activated my windows timer and tried to stop but it seems not to be working, please see my code:

private void button1_Click(object sender, EventArgs e)
{
        timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
        MessageBox.Show("Hello");
        timer1.Stop();
}

It shows the message over and over again and it doesn't stop. Please give me some ideas, I am very grateful for your help.

Upvotes: 0

Views: 404

Answers (2)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

You need to stop the timer before showing the message box. Otherwise they may pile up.

There is the System.Timers.Timer that can be configured to be a one-shot timer, but the general approach for other timers is:

When the timer event fires, stop the timer, do your thing and then start the timer again if needed.

Upvotes: 2

Ali Ezzat Odeh
Ali Ezzat Odeh

Reputation: 2163

At line MessageBox.Show("Hello"); The execution will stop there waiting for the user to press "OK" button, so line timer1.Stop(); won't be reached until user interacts with the message box, and the timer will continue to work this way.

Upvotes: 0

Related Questions