.NET - Timer Elapsed Event Overlap

1.6k Views Asked by At

Is there a way to detect that elapsed events of timer are overlapping? For example, I create a Timer with 200ms interval between elapsed events but the executed code at event is taking more than 200ms. As a result, another elapsed event is executed before the last one is finished. Also is there a way to prevent this from happening such that another event is not invoked before the last one is finished?

3

There are 3 best solutions below

0
On BEST ANSWER

If you want your timer events to happen on the 200ms mark and just skip one (rather than postpone them) if the previous is still running then you could use locking code.

If you use the method Monitor.TryEnter then it will return a boolean telling you if it has got the lock (and thus if another thread is already in the locked code). This will enable you to just skip over and wait for the next run time if you want (or write out debug messages complaining that its taking too long or something).

Whether this is a good solution really depends on what your timer is wanting to do. Often the method others have suggested of starting the timer for the next event once the previous one finishes is more than sufficient for the job.

0
On

Have a look at using Timer.Stop Method

0
On

If you want to fire the next cycle after the current one has finished, stop the timer if it hits it's tick event, and restart it if you're done.

Timer fires Tick-Event
    Disable/Stop Timer
    Program logic goes here
    Restart Timer