tags:

views:

74

answers:

4

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.

+3  A: 

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();
    }
Larsenal
+7  A: 

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
Justin Niessner
This is what I wanted to do and you answered correctly first, so a big check!
Yom
+1  A: 

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 true. This should do exactly what you want.

time.AutoReset = true;

The other option is to call Stop in the event handler.

Enigmativity
A: 

You may also use the System.Threading.Timer. Its constructor takes two time-related parameters:

  • The delay before the first "tick" (due time)
  • The period

Set the period to Timeout.Infinite to prevent from firing again.

Johann Blais