简体   繁体   中英

How to run a timer in C# only once?

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.

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

ie:

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

My favorite technique is to do this...

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

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

add

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

after

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

timer.Dispose()放在操作前的Tick方法中(如果操作等待用户的respose,即你的MessageBox,那么计时器将继续直到他们响应)。

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM