Yavs
Yavs

Reputation: 31

C# and how to use "System.Timers"

I recently started to use C# and I wanted to use timers.

I read Windows help about how to declare and define a Timer. What I don't understand is why I need the Console.ReadLine(); line to start the timer. (Link to the example)

// Firstly, create a timer object for 5 seconds interval 
timer = new System.Timers.Timer();
timer.Interval = 5000;

// Set elapsed event for the timer. This occurs when the interval elapses −
timer.Elapsed += OnTimedEvent;
timer.AutoReset = false;
// Now start the timer.
timer.Enabled = true;

Console.ReadLine(); // <------- !!!

What I want to do but I don't achieve is to start the timer as soon as it is declared. I dont want to write Console.ReadLine(); because I may not need a console.

Example: If i develop a timer class and I call it from an other class, how can I check the timer has been completed?

Thank you in advance.

Upvotes: 1

Views: 12024

Answers (1)

Almaran
Almaran

Reputation: 170

You need to set Timer, than wait for time is elapsed which executes the OnTimedEvent, that is how you can check if it already elapsed.

    // Create a timer with a two second interval.
    timer = new System.Timers.Timer(2000);
    // Hook up the Elapsed event for the timer. 
    timer.Elapsed += OnTimedEvent;
    timer.AutoReset = true;
    timer.Enabled = true;

The OnTimedEvent should look like this:

private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                      e.SignalTime);
}

If you need to Stop the timer you should call:

   timer.Stop();
   timer.Dispose();

You need Console.ReadLine(); just for not exiting the main method and the whole program. If you're developing something else like MVC or WPF, you don't need it.

Upvotes: 3

Related Questions