Smart Dispatcher – Getting Back to the UI Thread
When you work with Silverlight classic or for Windows Phone everyday like I do, you get used writing code that helps you get back on the UI thread when needed.
I was chatting with Jeff Wilcox about threading and I tossed this code at him, as Jeff also has a SmartDispatcher class. Mine is a much smaller feature set than Jeff’s, but it does the job I need. Anyway, the discussion with Jeff made me realize I had not shared this code.
Sometimes your code runs on a background thread, for example, and you need to do something to the UI. But you are on the background thread and can’t affect the UI from there, so what do you do? You use the Dispatcher (or SynchronizationContext class) to help you get back to the UI thread. There are several ways to do this, but the most common one I use is via a SmartDispatcher class I created recently.
I admit that until I created this class I was rewriting the code in every place I needed it. Not a good thing. So recently I created this class with a single method, BeginInvoke. It checks if I am running in the designer or if I am already on the UI thread. If either is true, I just run the Action since there is no need to use the Dispatcher. If I’m at runtime and I am not on the UI thread, I execute the Action through the Dispatcher. Pretty simple.
public class SmartDispatcher
{
public static void BeginInvoke(Action action)
{
if (Deployment.Current.Dispatcher.CheckAccess()
|| DesignerProperties.IsInDesignTool)
{
action();
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(action);
}
}
}
So any place I need to execute on the UI thread I do something like this:
SmartDispatcher.BeginInvoke(() =>
{
IsBusy = false;
Widgets = widgetsResponseSet;
});