Reliable timer in a console application

C#.Netvb.netTimer

C# Problem Overview


I am aware that in .NET there are three timer types (see Comparing the Timer Classes in the .NET Framework Class Library). I have chosen a threaded timer as the other types can drift if the main thread is busy, and I need this to be reliable.

The way this timer works in the control of the timer is put on another thread so it can always tick along with the work begin completed on the parent thread when it is not busy.

The issue with this timer in a console application is that while the timer is ticking along on another thread the main thread is not doing anything to the application closes.

I tried adding a while true loop, but then the main thread is too busy when the timer does go off.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnView Question on Stackoverflow
Solution 1 - C#huseyintView Answer on Stackoverflow
Solution 2 - C#Greg HurlmanView Answer on Stackoverflow
Solution 3 - C#user14291542View Answer on Stackoverflow