Silverlight: Binding and Threading == Cat and Dog

Introduction

Let me start by thanking Ian Griffiths for the brilliant course that he delivered to me in London this week on Silverlight. Ian you’re the man!!! Ok having said that we can now start :)

Just like in WPF, threading and databinding in Silverlight have a Cat – Dog relationship. This is due to the fact that when a binding notification is raised from a separate thread than the Dispatcher thread, an exception is thrown. The exception is thrown because the binding is trying to modify the a UI element from a separate thread than the Dispatcher thread. In Silverlight this is even a bit worse than it is in WPF because an exception is raised even when the notification is from an INotifyPropertyChanged. Another miss leading thing in Silverlight is that, the exception thrown when a binding notification is raised from a separate thread is of type System.UnauthorizedAccessException (you can see this in the Visual Studio Output window). Hmmm … We WPF guys are used to see the InvalidOperationException for this but anyway…

Ok so till now we determined that both INotifyPropertyChanged and INotifyCollectionChanged will explode if they raise the binding notification from a separate thread than the UI thread so let’s see how to work around this.

In WPF one can get the Dispatcher instance by calling Application.Current.Dispatcher or by saying Dispatcher.CurrentDispatcher but guess what; both of these are not included in Silverlight. Don’t worry we still can get Mr. Dispatcher, we need to call the Application.Current.RootVisual.Dispatcher (keeping in mind not to call RootVisual from a seperate thread than the Dispatcher thread otherwise BAMMMM).

Brilliant, we have the dispatcher but guess what the only method that you can see (in the VS intellisense) in the Dispatcher is BeginInvoke !! This will not help much since we need a CheckAccess method that can check for us if the executing thread is the dispatcher thread. After drilling into the Dispatcher class, I found that a CheckAccess method actually exits in the Dispatcher class but for some strange reason it is decorated with this attribute -> [EditorBrowsable(EditorBrowsableState.Never)] to hide it from us developers. I guess this means that it is subject to change in the very near future …

Anyway, now that we know how to get the Dispatcher instance and how to check if the executing thread is the dispatcher thread we can get to work. Lets’ start by fixing the INotifyPropertyChanged issue.

Fixing INotifyPropertyChanged

This will be quite easy, we will need to make the object raise the binding notification on the dispatcher thread. I created a base class that will do this for you… It is very simple have a look yourself.

/// <summary>
/// Base class for objects that need to raise property change notification from seperate threads
/// </summary>
public abstract class ThreadableBindableObject : INotifyPropertyChanged
{
    private Dispatcher currentDispatcher;
 
    /// <summary>
    /// default constructor
    /// Here we must get the Dispatcher object
    /// </summary>
    public ThreadableBindableObject()
    {
        if (Application.Current != null &&
                                Application.Current.RootVisual != null &&
                                Application.Current.RootVisual.Dispatcher != null)
        {
            currentDispatcher = Application.Current.RootVisual.Dispatcher;
        }
        else // if we did not get the Dispatcher throw an exception
        {
            throw new InvalidOperationException("This object must be initialized after that the RootVisual has been loaded");
        }
 
    }
 
    #region INotifyPropertyChanged Members
 
    /// <summary>
    /// Event raised to notify listeners that a property changed
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;
 
    /// <summary>
    /// raises the PropertyChanged on the dispatcher thread
    /// This will only switch to the Dispatcher thread if the Dispatcher is available via the RootVisual
    /// </summary>
    /// <param name="propertyName">The property name to raise the event</param>
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            //check if we are on the UI thread if not switch
            if (currentDispatcher.CheckAccess())
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            else
                currentDispatcher.BeginInvoke(new Action<string>(OnPropertyChanged), propertyName);
        }
    }
 
    #endregion
}

 

So basically this base class will go ahead and implement the INotifyPropertyChanged interface for you and make sure that before the PropertyChanged event is raised we are on the Dispatcher thread. One would ask why are we getting the dispatcher instance in the constructor of the object, well the answer is that, we cannot get the Dispatcher instance from the OnPropertyChanged method because that method will be called from non dispatcher threads and if you call the Application.Current.RootVisual from a non dispatcher thread BAMMM… everything explodes because you are trying to access a UI element from a non dispatcher thread. Ok so now that we have this class we can go ahead and use it by inheriting from it; something like this I would say

public class Person : ThreadableBindableObject
{
    private string name;
 
    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            OnPropertyChanged("Name");
        }
    }
 
    private string surname;
 
    public string Surname
    {
        get { return surname; }
        set
        {
            surname = value;
            OnPropertyChanged("Surname");
        }
    }
}

 

Fixing INotifyCollectionChanged

When it comes to the INotifyCollectionChanged we want to avoid to re invent the wheel and implement the INotifyCollectionChanged interface ourselves so what we are going to do is to inherit from the ObservableCollection<T> and override the base methods for the Insert, Remove, Clear and Set. We will also need to override the OnPropertyChanged. This is nothing new, Beatriz Costa the WPF Queen, did this a while ago in the WPF world so; NO, I am not inventing anything here I am just being a messenger :)

So here is the code for the new ObservableCollection… I called it ThreadableObservableCollection<T> so that it sounds complex :D

/// <summary>
/// Collection that supports INotifyCollectionChanged notification from seperate threads
/// </summary>
/// <typeparam name="T">The type of object to store in the collections</typeparam>
public class ThreadableObservableCollection<T> : ObservableCollection<T>
{
    private Dispatcher currentDispatcher;
 
    /// <summary>
    /// default constructor
    /// Here we must get the Dispatcher object
    /// </summary>
    public ThreadableObservableCollection()
    {
        if (Application.Current != null &&
                                Application.Current.RootVisual != null &&
                                Application.Current.RootVisual.Dispatcher != null)
        {
            currentDispatcher = Application.Current.RootVisual.Dispatcher;
        }
        else // if we did not get the Dispatcher throw an exception
        {
            throw new InvalidOperationException("This object must be initialized after that the RootVisual has been loaded");
        }
    }
 
    protected override void InsertItem(int index, T item)
    {
        if (currentDispatcher.CheckAccess())
            base.InsertItem(index, item);
        else
            currentDispatcher.BeginInvoke(new Action<int, T>(InsertItem), index, item);
    }
 
    protected override void ClearItems()
    {
        if (currentDispatcher.CheckAccess())
            base.ClearItems();
        else
            currentDispatcher.BeginInvoke(new Action(ClearItems));
    }
 
    protected override void RemoveItem(int index)
    {
        if (currentDispatcher.CheckAccess())
            base.RemoveItem(index);
        else
            currentDispatcher.BeginInvoke(new Action<int>(RemoveItem), index);
    }
 
    protected override void SetItem(int index, T item)
    {
        if (currentDispatcher.CheckAccess())
            base.SetItem(index, item);
        else
            currentDispatcher.BeginInvoke(new Action<int, T>(SetItem), index, item);
    }
 
    protected override void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (currentDispatcher.CheckAccess())
            base.OnPropertyChanged(e);
        else
            currentDispatcher.BeginInvoke(new Action<PropertyChangedEventArgs>(OnPropertyChanged), e);
    }
}

As you can see there is nothing to it. We are just overriding the base methods Insert, Remove, Clear and Set so that we make sure that they will get called on the Dispatcher thread. These methods are the methods that raise the CollectionChanged event so by forcing them to run on the Dispatcher thread we are ensuring that the binding will potentially work (hihi … what a paradox). We are also doing this for the OnPropertyChanged method of course.

Conclusion

Yea, the conclusion is threading can be pain full especially when dealing with UI but that’s life :)

 

Download Sample Source