Reliable timer in console application

I know that there are three types of timers in .NET (see Comparing Timer Classes in the .NET Framework Class Library ). I chose a multi-threaded timer, as other types can drift if the main thread is busy, and I need it to be reliable.

The way this timer works in timer control is placed in another thread, so it can always tick off with the start of work completed in the parent thread when it is not busy.

The problem with this timer in the console application is that while the timer is running in another thread, the main thread does nothing to shut the application down.

I tried to add a while true , but then the main thread is too busy when the timer goes off.

+86
c # timer
Aug 01 '08 at 12:43
source share
2 answers

You can use something like Console.ReadLine() to lock the main thread, so other background threads (like timer threads) will still work. You can also use AutoResetEvent to block execution, then (when you need to) you can call the Set () method on this AutoResetEvent object to free the main thread. Also, make sure your reference to the Timer object does not go out of scope and garbage.

+53
Aug 01 '08 at 12:56
source share

Using ManualResetEvent, block the main thread at the end of its processing and call Reset() on it after the timer has finished processing. If this is something you need to constantly run, consider moving it to a service process instead of a console application.

+19
Aug 01 '08 at 12:55
source share



All Articles