Let's say I have an existing instance of System.Threading.Timer, and I would like to call Change on it in order to click on the firing time:
var timer = new Timer(DelayCallback, null, 10000, Timeout.Infinite);
I use this timer to perform an “idle callback” after a period of inactivity. ("Idle" and "no activity" are the conditions defined by the application in this case ... the features are not very important.) Every time I perform an "action", I want to reset the timer so that it always fires 10 seconds after of this.
However, there is an inherent condition for the race, because when I call Change, I can’t say whether Timer has already been launched based on its old settings. (I can, of course, say whether my callback has occurred, but I cannot say whether the CLR internal timer thread has called my callback in threadpool, and its execution is inevitable.)
Now I know that I can call Dispose on the timer instance and recreate it every time I need to push it. but it seems less effective than just modifying an existing timer. Of course, this may not be so ... I ran a few micro tests a bit and let you know.
Alternatively, I can always track the expected firing time (via DateTime.Now.AddSeconds (10)), and if the original timer fires, ignore it by checking DateTime.Now in the callback. (I have a suspicious concern that this may not be 100% reliable due to a timer using TimeSpan and my checking using DateTime ... this may not be a problem, but I'm not quite comfortable with it for some reason reason ...)
My questions:
- Is there a good way to call Timer.Change and find out if I managed to change it before the callback was queued on threadpool? (I don’t think so, but it’s not painful to ask ...)
- Has anyone else implemented (what I call) a "pushing timer" like this? If so, I would like to hear how you solved the problem.
This question is somewhat hypothetical in nature, since I already have several working solutions (based on Dispose and based on DateTime.Now) ... I am mainly interested in rumors about offers related to performance (since I will “drop” the timer Often).
Thanks!
user42286
source share