Loek Ouweland has recently blogged about more responsive UI operations utilising the
BackgroundWorker class. To put it simple: if you execute your code on the same thread as the UI, then the UI won’t be updated/re-drawn until the execution is finished. This is actually not a new problem to WP7, it’s a common behavior of almost all platforms out there.
The example in Loek’s post is a
for loop that generates many star patterns on the UI. During the generation process, Loek wanted to show the progress of the generation using a progress bar. The progress bar would never change during the for loop because the loop happens on the same UI thread, which prevents the UI from being updated until all of the stars are added to the UI. The solution was to use a
BackgroundWorker to perform the loop and in each loop use the
Dispatcher object of the UI thread to add the star to the UI.
While this seemed to be working just fine, there’s an obvious limitation in this approach, that all UI element related operations still need to happen on the UI thread.
Let’s take Loek’s example again. The reason why Dispatcher is used in the
BackgroundWorker solution is that you can’t directly access objects on the UI thread from another thread.
Usually, where you really want to use this technique is when you have a large amount of complex UI elements that you need to generate using a loop in the code behind. The limitation of this approach is, that you are neither able to access the UI layer nor able to generate any UI elements in the background thread and pass them to the UI thread. As soon as you try to create any object that inherits the
DependencyObject class in the background thread, you’ll get the same Invalid cross-thread access exception.
Which means, you may give your UI a chance to update itself between the moment of jumping to the next loop, but you may still experience UI freeze up while you use
Dispatcher to generate that complex UI element inside each loop, depends on how complex the UI element is.