12

I want a timer in C# to destroy itself once it has executed. How might I achieve this?

private void button1_Click(object sender, EventArgs e)
{
    ExecuteIn(2000, () =>
    {
        MessageBox.Show("fsdfs");   
    });           
}

public static void ExecuteIn(int milliseconds, Action action)
{
    var timer = new System.Windows.Forms.Timer();
    timer.Tick += (s, e) => { action(); };
    timer.Interval = milliseconds;
    timer.Start();

    //timer.Stop();
}

I want this message box to show only once.

leppie
  • 115,091
  • 17
  • 196
  • 297
user1747819
  • 301
  • 1
  • 5
  • 11

6 Answers6

33

use the Timer.AutoReset property:
https://msdn.microsoft.com/en-us/library/system.timers.timer.autoreset(v=vs.110).aspx

i.e:

System.Timers.Timer runonce=new System.Timers.Timer(milliseconds);
runonce.Elapsed+=(s, e) => { action(); };
runonce.AutoReset=false;
runonce.Start();

To stop or dispose the Timer in the Tick method is unstable as far as I am concerned

EDIT: This doesn't work with System.Windows.Forms.Timer

jorx
  • 481
  • 5
  • 7
17

My favorite technique is to do this...

Task.Delay(TimeSpan.FromMilliseconds(2000))
    .ContinueWith(task => MessageBox.Show("fsdfs"));
7

Try stopping the timer as soon as it enters Tick:

timer.Tick += (s, e) => 
{ 
  ((System.Windows.Forms.Timer)s).Stop(); //s is the Timer
  action(); 
};
Jens Kloster
  • 11,099
  • 5
  • 40
  • 54
0

add

timer.Tick += (s, e) => { timer.Stop() };

after

timer.Tick += (s, e) => { action(); };
mehdi.loa
  • 579
  • 1
  • 5
  • 23
0

Put timer.Dispose() it in the method for Tick before the action (if the action waits on a user's respose i.e. your MessageBox, then the timer will continue until they've responded).

timer.Tick += (s, e) => { timer.Dispose(); action(); };
Griknok
  • 384
  • 2
  • 13
0

In Intializelayout() write this.

this.timer1 = new System.Windows.Forms.Timer(this.components);
this.timer1.Enabled = true;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);

and in form code add this method

private void timer1_Tick(object sender, EventArgs e)
    {
        doaction();
        timer1.Stop();
        timer1.Enabled = false;
    }
Ritesh Khatri
  • 484
  • 4
  • 13