Threading.Timer with an autogrid or a single thread?

I want to create a class that reads SMS messages from a GSM device.

I created a timer (system.threading) that reads for an incoming message every second.

public void ReadMessage(){ //read sms messages //and store it into the database } 

Sometimes ReadMessage() takes more than a second. How can I prevent the timer from calling this procedure when the previous one is not over yet?
1. Are AutoResetEvent and WaitOne useful for this?
2. Is Threading.Timer a good choice? or should I do this in one thread?

+4
source share
3 answers

You should use System.Timers.Timer , which is easier to work with.
(This is a friendlier shell around Threading.Timer )

Set AutoReset to false , then the Start() timer again at the end of the handler.

Do not use dedicated stream; it makes no sense to keep the thread around doing nothing so you can wake it every second.

+4
source

Although this question is quite old, you can inspire with this code. It does not use an additional thread and does not take into account the time during the execution of your code.

 /// <summary> /// Single thread timer class. /// </summary> public class SingleThreadTimer: IDisposable { private readonly Timer timer; private readonly Action timerAction; /// <summary> /// Initializes a new instance of the <see cref="SingleThreadTimer"/> class. /// </summary> /// <param name="interval">The interval time.</param> /// <param name="timerAction">The timer action to execute.</param> /// <exception cref="System.ArgumentNullException">timerAction</exception> /// <exception cref="System.ArgumentException">interval</exception> public SingleThreadTimer(double interval, Action timerAction) { if (timerAction == null) throw new ArgumentNullException("timerAction"); if (interval <= 0) throw new ArgumentException(string.Format("Invalid value '{0}' for parameter 'interval'.", interval), "interval"); this.timerAction = timerAction; this.timer = new Timer(interval) { AutoReset = false }; timer.Elapsed += timer_Elapsed; timer.Start(); } public void Dispose() { if (timer != null) timer.Dispose(); } private void timer_Elapsed(object sender, ElapsedEventArgs e) { try { timerAction(); } finally { // Enable timer again to continue elapsing event. timer.Enabled = true; } } } 
+2
source

I do not see any need for an explicit timer trigger. If you miss this:

 while(true){ ReadMessage(); Thread.Sleep(1000); }; 

.. it does not do what you want, everything is beautifully enclosed in one stream?

Rgds, Martin

+1
source

All Articles