Recipe 18.8. Configuring a TimerProblemYou have one of the following timer configuration needs:
SolutionTo fire a System.Threading.Timer after an initial delay, and then at a specified period after that, use the System.Threading.Timer constructor to set up different times for the initial and following callbacks, as shown in Example 18-5. Example 18-5. Configuring a timer
The previous method showed how to fire the callback after 500 milliseconds. To fire the initial callback immediately, change the value to zero: // Create a timer that doesn't wait, then invokes // the callback every second thereafter. Timer timer = new Timer(callback, null,0, 1000); To have the timer call the callback only once, change the constructor to pass Timeout.Infinite for the second callback interval. You also have to change the current scheme that waits for five callbacks before disposing of the timer to do it the first time. If you didn't do this, the program will hang, since the Main function is still waiting for the timer to have Dispose called, but the fifth callback will never trigger the Dispose call: // Create a timer that waits for half a second, then is disposed. Timer timer = new Timer(callback, null,500, Timeout.Infinite); static void TimerMethod(Object state) { timerRef.Dispose( ); } To change the interval of a running System.Threading.Timer, call the Change method specifying the delay before the next callback and the new callback interval, like this: static void TimerMethod(Object state) { count++; if(count == 5) { timerRef.Change(1000,2000); } if(count == 10) { timerRef.Dispose( ); } } This code now checks for the fifth callback and changes the interval from 1 second to 2 seconds. The sixth callback will happen 1 second after, and then callbacks through 10 will happen 2 seconds apart. DiscussionOne item to be aware of when using System.Threading.Timers and TimerCallbacks is that they are serviced from the ThreadPool. This means that if you have other work being farmed out to the ThreadPool in your application, it could be contending with the Timer callbacks for an available worker thread. The basic timer is enough to serve the earlier scenarios, but if you are doing UI work and want to use timers, you should investigate the System.Windows.Forms.Timer class. If you are doing server work, you might also want to look at System.Timers.Timer as well. Both of these classes add events for when the timers are disposed and when the timer "ticks"; they also add properties that expose the settings. See AlsoSee the "System.Threading.Timer Class," "TimerCallback Delegate," "System.Windows. Forms.Timer Class," and "System.Timers.Timer" topics in the MSDN documentation. |