Reputation: 53
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.
Upvotes: 5
Views: 28197
Reputation: 117010
I assume that you're using System.Timers.Timer
rather than System.Windows.Forms.Timer
?
You have two options.
First, as probably the best, is to set the AutoReset
property to false
. This should do exactly what you want.
time.AutoReset = false;
The other option is to call Stop
in the event handler.
Upvotes: 2
Reputation: 9469
You may also use the System.Threading.Timer. Its constructor takes two time-related parameters:
Set the period to Timeout.Infinite to prevent from firing again.
Upvotes: 1
Reputation: 245369
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
Upvotes: 23
Reputation: 51146
A little example app:
static void Main(string[] args)
{
int seconds = 2;
Timer time = new Timer(seconds * 1000); //to milliseconds
time.Enabled = true;
time.Elapsed += new ElapsedEventHandler(MyHandler);
time.Start();
Console.ReadKey();
}
private static void MyHandler(object e, ElapsedEventArgs args)
{
var timer = (Timer) e;
timer.Stop();
}
Upvotes: 3