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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With