Alex T Alex T - 3 months ago 11
C# Question

System.Windows.Forms.Timer keeps on running c#

I need to show a message after 10 seconds of form load.
I am using the below code

private void Form1_Load(object sender, EventArgs e)
{
SetTimeInterval();
}

System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();

public void SetTimeInterval()
{
MyTimer.Interval = ( 10 * 1000);
MyTimer.Tick += new EventHandler(TimerEventProcessor);
MyTimer.Start();
}

void TimerEventProcessor(Object myObject,EventArgs myEventArgs)
{
MessageBox.Show("TIME UP");
MyTimer.Stop();
MyTimer.Enabled = false;
}


Tried using MyTimer.Stop() and MyTimer.Enabled = false, but messagebox keeps displaying every 10 seconds. How do I stop it after the first instance?

Answer

Your problem is that MessageBox.Show() is a blocking call. So MyTimer.Stop() is only called after you close the MessageBox.

So until you closed the MessageBox there will pop up new ones every 10s. The simple solution is to change the order of calls:

void TimerEventProcessor(Object myObject,EventArgs myEventArgs)
{
    MyTimer.Stop();
    MyTimer.Enabled = false;
    MessageBox.Show("TIME UP");           
}

So the timer is stopped as soon as you enter the event handler, before displaying the message box.