1

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.

3
  • 5
    The Console.ReadLine is not there to start the timer but to stop the program from exiting. Commented Jan 29, 2020 at 7:37
  • 1
    Console.ReadLine(); prevent the application from exiting before the timer expires. Commented Jan 29, 2020 at 7:38
  • Is your app a console application? A WPF application? Something else? What do you need a timer for in the first place? Judging by your "Example" I feel like a timer might not be the best thing to use here... Commented Jan 29, 2020 at 7:52

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Does private static void OnTimedEvent need to be static?
@gouderadrian It is not necessary. I have it this way because it was in static class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.