Understanding Threading In Avalon

Here’s a thread in the Avalon newsgroup that I was participating in that shows why it’s important to put any kind of long operations on a background thread. Basically if you’re familiar with the threading model of WinForms then you know you need to put long running operations on a background thread and marshal calls to update the UI on the main thread using Control::Invoke so that you do not cause your program to become unresponsive to input or screen painting. Well, Avalon shares the same concepts…

Instead of Control, which is the base of all UI elements in WinForms, we have a base class in Avalon called DispatcherObject. DispatcherObject has a propety called Dispatcher which returns the Dispatcher instance (surprise!) that this object is tied to. Dispatcher is the class that controls the message pumping aspects for a thread and, as such, is where Invoke and its async equivalents, Begin/EndInvoke, are now exposed. You’ll notice one major difference between Dispatcher::Invoke and Control::Invoke, every overload of Dispatcher::Invoke takes a DispatcherPriority as its first parameter. This allows you to efficiently schedule tasks with the Dispatcher so that, for example, they are synchronized with other intrinsic Avalon operations such as loading, data-binding, rendering, etc. So in the case where you’re trying to update your UI from a background thread you would probably choose DispatcherPriority.Render so that the message is pumped when the renderer is ready to process new rendering instructions.

Two other things I should probably mention are that the WinForms Timer equivalent in Avalon is called DispatcherTimer and currently there is no equivalent of the BackgroundWorker class in Avalon although I had written one for the older builds of Avalon so eventually I’ll get around to upgrading it to the latest API changes. 🙂

Anyway, definitely check out that thread in the newsgroups and here’s a direct link to the sample I attached to one of my replies to demonstrate the difference in behavior.

Leave a Reply