0
votes

I'm wondering if there is some way to temporarily pause a timer and then restart it.

I have a method "DoSomething()" which can be called from within a timer event or within a different method called "Chooser()". DoSomething() should be called from the timer OR Chooser(), but it shouldn't be called twice.

The problem is that it takes some time for Chooser() to decide if it should call DoSomething(). DoSomething() shouldn't be called while Chooser() is deciding if it should also call DoSomething(). This would result in DoSomething() being called twice.

If Chooser() does choose to call DoSomething() it will disable the timer. Likewise, if the timer calls DoSomething() it will disable the code within Chooser().

I was thinking of removing the timer eventhandler at the start of Chooser() and then re-adding it at the end of Chooser(). However, this doesn't work because the timer might trigger the event while Chooser() is running, and the event will not be handled.

I don't think I can use a lock, because I only want to call DoSomething() once.

It'd be ideal if I could just pause the timer at the start of Chooser() and then start it again at the end, but I don't believe that possibility exists.

I could just add a flag, but I was wondering if there's anything better.

1
There is a small window where it's possible for a Timer to fire AFTER it has been stopped. Consider that possibility in your solution. - hatchet - done with SOverflow

1 Answers

0
votes

Set a flag under a lock that signals that DoSomething is running. Also under the lock, test whether that flag is already set. If yes, just return and do nothing.

It is not possible to reliably stop timers. Tick events can be delivered arbitrarily even after stopping the timer, even concurrently (multiple ticks at the same time).