Yom
Yom

Reputation: 53

How to stop a timer after it is done running?

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

Answers (4)

Enigmativity
Enigmativity

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

Johann Blais
Johann Blais

Reputation: 9469

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.

Upvotes: 1

Justin Niessner
Justin Niessner

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

Larsenal
Larsenal

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

Related Questions