Using a timer to do periodic updates
It is sometimes useful to update parts of the user interface periodically. For example, an application may need to display the current time in some part of the UI. Or some color changes need to be made on a regular basis based on some runtime criteria. Although it's possible to create a thread that sleeps for a certain amount of time and then does the updates, this has two flaws: the first is that most of the time the thread sleeps. Threads are supposed to do useful work and not sleep most of the time – the very fact the thread exists requires it to have its stack space (1MB by default), which may be wasteful in such a case. The second flaw is that we would have to marshal the UI update call using some mechanism we've already seen (Dispatcher
, SynchronizationContext
, and so on), which makes the code cumbersome.
A timer can be used instead if such updates are required, without the need to create additional threads. In this recipe, we'll use the DispatcherTimer...