Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a timer in C# only once?

Tags:

c#

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.

like image 818
user1747819 Avatar asked May 30 '13 05:05

user1747819


1 Answers

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

like image 90
jorx Avatar answered Sep 16 '22 14:09

jorx