At least for me, this is the perfect example of using System.Timers.Timer
. The only problem is that it will not work if I eliminate Console.ReadLine()
. In my case, I just want to display a message after 5 seconds have passed and then the console will close. That's it.
So let's say that I want to display simple message Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime)
without any user interaction, how would I be able to do that? In other words, when I hit F5, I'll see the blank console window, in 5 seconds I will see the message, and then the console will go away.
Here's the code from MSDN:
using System;
using System.Timers;
public class Example
{
private static Timer aTimer;
public static void Main()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(5000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program... ");
Console.ReadLine();
Console.WriteLine("Terminating the application...");
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
}