views:

1095

answers:

2

I am aware in dot net there are three timer types (see http://msdn.microsoft.com/en-us/magazine/cc164015.aspx). I have chosen a the 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 I have is that 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 so the app closes.

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

Any ideas welcome.

+2  A: 

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 constantly, consider moving this into a service process instead of a console app.

Greg Hurlman
+4  A: 

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.

huseyint
I think maybe you mean Console.ReadLine() ?
Cheeso
yeah, thanks, fixed :)
huseyint