Reliable timer in a console application

According to MSDN and the other answers, a minimal working example of a Console application using a System.Threading.Timer without exiting immediately :

private static void Main()
{
    using AutoResetEvent autoResetEvent = new AutoResetEvent(false);
    using Timer timer = new Timer(state => Console.WriteLine("One second has passed"), autoResetEvent, TimeSpan.Zero, new TimeSpan(0, 0, 1));
    autoResetEvent.WaitOne();
}

You can use something like Console.ReadLine() to block the main thread, so other background threads (like timer threads) will still work. You may also use an AutoResetEvent to block the execution, then (when you need to) you can call Set() method on that AutoResetEvent object to release the main thread. Also ensure that your reference to Timer object doesn't go out of scope and garbage collected.


Consider using a ManualResetEvent to block the main thread at the end of its processing, and call Reset() on it once the timer's processing has finished. If this is something that needs to run continuously, consider moving this into a service process instead of a console app.