13

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.

0

6 Answers 6

34

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

Sign up to request clarification or add additional context in comments.

1 Comment

For a difference between timers stackoverflow.com/a/4532859/1737819
17

My favorite technique is to do this...

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

2 Comments

this is better than a timer by far.
Use System.Threading.Tasks.TaskEx instead of Task if you target .NET 4.0 stackoverflow.com/questions/35041478/await-async-taskex/…
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(); 
};

1 Comment

AutoReset is a better solution
0

add

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

after

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.