Reputation: 311
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.
Upvotes: 13
Views: 33081
Reputation: 181
My favorite technique is to do this...
Task.Delay(TimeSpan.FromMilliseconds(2000))
.ContinueWith(task => MessageBox.Show("fsdfs"));
Upvotes: 17
Reputation: 491
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
Upvotes: 34
Reputation: 484
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;
}
Upvotes: 0
Reputation: 386
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(); };
Upvotes: 0
Reputation: 11277
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();
};
Upvotes: 7
Reputation: 575
add
timer.Tick += (s, e) => { timer.Stop() };
after
timer.Tick += (s, e) => { action(); };
Upvotes: 0