Question

I have an application behaving like autorefresh. It checks emails, new videos, jokes, etc.

My client wants these single elements check in different intervals. For example emails every minute, videos every hour, etc. So there should be option for him to write down intervals by himself into textboxes and by checking appropriate checkbox start/stop refreshing.

Application is written in wpf. My question is, whether is better option to add more DispatcherTimers(DT), one for each of elements or stick with only one DT and in tick function make switch?

Also, I assume that DT's tick method runs main thread. Am I right? Is it better to run operations inside tick method on different thread if possible?

Was it helpful?

Solution

By default WPF Application has single thread - Main UI thread and all UI controls/windows are created and associated with it. In this case I do not see any benefits usign multiple Dispatchers and Dispatcher Timers since anyway Dispatcher Timer would delegate all messages to the associated Dispatcher's messages loop what would be a Main UI thread message loop.

But if you've created some controls in separate worker threads like

var thread = new Thread(() => 
         {  
              CustomWindow wnd = new CustomWindow();  
         };

And would post messages to this window as well - then it makes sense creating a new Dispatcher and associating with a manually created thread, so basically each Dispatcher will be associated with own thread, so relation is 1 to 1.

Regarding atick method - it would be executed on the associated with Dispatcher thread. If you've not created dispatcher associated with a manually created worker thread, so by default WPF Dispatcher associated with the main UI thread,

MSDN:

Reasons for using a DispatcherTimer opposed to a System.Timers.Timer are that the DispatcherTimer runs on the same thread as the Dispatcher and a DispatcherPriority can be set on the DispatcherTimer

OTHER TIPS

Make it as simple as possible. As long as it is not time-consuming to check for new elements, simply use one DispatcherTimer with its own Tick handler per element category (and of course if you don't have hundreds of categories).

If the check operation is time-consuming it would block the Tick handler and thus the UI thread. Then you could use one System.Timers.Timer per element category and perform the check for new elements in the Timer's Elapsed handler (instead of Tick). Since the timers run on different threads (from the thread pool) you would have to synchronize with the UI thread:

private void VideosTimerElapsed(object sender, ElapsedEventArgs e)
{
    // check for new videos...
    Dispatcher.BeginInvoke(new Action(UpdateUI));
}

private void UpdateUI()
{
    // update UI components
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top