Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a timer after it is done running?

Tags:

c#

timer

I have a Console App and in the main method, I have code like this:

Timer time = new Timer(seconds * 1000); //to milliseconds
time.Enabled = true;
time.Elapsed += new ElapsedEventHandler(time_Elapsed);

I only want the timer to run once so my idea is that I should stop the timer in the time_Elapsed method. However, since my timer exists in Main(), I can't access it.

like image 373
Yom Avatar asked Sep 16 '10 00:09

Yom


1 Answers

You have access to the Timer inside of the timer_Elapsed method:

public void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    Timer timer = (Timer)sender; // Get the timer that fired the event
    timer.Stop(); // Stop the timer that fired the event
}

The above method will stop whatever Timer fired the Event (in case you have multiple Timers using the same handler and you want each Timer to have the same behavior).

You could also set the behavior when you instantiate the Timer:

var timer = new Timer();
timer.AutoReset = false; // Don't reset the timer after the first fire
like image 122
Justin Niessner Avatar answered Oct 02 '22 16:10

Justin Niessner