Skip to main content

WP7Contrib: Thread safe ObservableCollection<T>

Continuing with the introduction of WP7Contrib concepts, patterns & services from my previous post I thought I would explain why we have chosen to implement our own ObservableCollection.

As with the desktop version of Silverlight the idea of a 'blocking call' on the UI thread is discouraged, to point where if you do block the UI thread on a WP7 device your application could be automatically torn down - bad user experience. So to get round the issue the Silverlight framework makes use of the standard .Net 'async pattern' - IAsyncResult interface. Examples of this are the HttpWebRequest class and it's counterpart HttpWebResponse, they allow you to execute web requests without blocking the UI thread.

The problem with the ObservableCollection<T> supplied by the framework is it's not thread safe for any methods. For example, when you have a control bound to the collection and it's enumerating over the collection and another thread modifies the collection you'll receive the exception - "Collection was modified; enumeration operation may not execute.". It could be said this is an oversight of the implementation but I wouldn't go that far, the idea of copying the internal list for every call to GetEnumerator could be an expensive time & memory operation.

We required a thread safe version of an ObservableCollection<T> so that meant rolling our own. The first thing we defined where the interfaces we needed, the obvious ones being the INotifyCollectionChanged & INotifyPropertyChanged.

/// <summary>
/// Marker interface for the observable collection.
/// </summary>
public interface IObservableCollection
{
}

/// <summary>
/// Generic interface for observable collection
/// </summary>
/// <typeparam name="T">The type being used for binding.
/// </typeparam>
public interface IObservableCollection<T> : IList<T>, IObservableCollection, INotifyCollectionChanged, INotifyPropertyChanged
{
/// <summary>
/// Adds a range of items to the observable collection.
/// </summary>
/// <param name="items">
/// The items to be added to the observable collection.
/// </param>
void AddRange(IEnumerable<T> items);
}

The implementation of these interfaces are the ObservableCollection we developed.

We use the composition principle to store the items of collection internally in a List<T> implementation.

/// <summary>
/// Thread safe observable collection
/// </summary>
/// <typeparam name="T">The type being used for binding.
/// </typeparam>
public sealed class ObservableCollection<T> : BaseCollectionModel, IObservableCollection<T>
{
/// <summary>
/// The internal collection.
/// </summary>
private readonly IList<T> collection = new List<T>();

...
...
...
}

Synchronisation to all methods which could modify or enumerate the items is done using a Monitor critical section exposed via the 'lock' method.

Add Method:

/// <summary>
/// Adds an item to the collection, raises a RaiseCollectionChanged event with a NotifyCollectionChangedAction.Add
/// parameter.
/// </summary>
/// <param name="item">
/// The item being added.
/// </param>
public void Add(T item)
{
int index;

lock (this.sync)
{
this.collection.Add(item);
index = this.collection.IndexOf(item);
}

this.RaiseCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
}

Remove Method:

/// <summary>
/// Removes an item from the collection. If the item does not exist in the collection the false is returned.
/// </summary>
/// <param name="item">
/// The item to be removed from the collection
/// </param>
/// <returns>
/// Returns the result of removing an item from the collection, if the item existed it returns true else false.
/// </returns>
public bool Remove(T item)
{
int index;
bool result;

lock (this.sync)
{
index = this.collection.IndexOf(item);
if (index == -1)
{
return false;
}
result = this.collection.Remove(item);
}

if (result)
{
this.RaiseCollectionChanged(NotifyCollectionChangedAction.Remove, item, index);
}

return result;
}

Clear Method:

/// <summary>
/// Clears the contents of the collection, raises a RaiseCollectionChanged event with a NotifyCollectionChangedAction.Reset
/// </summary>
public void Clear()
{
lock (this.sync)
{
this.collection.Clear();
}

this.RaiseCollectionChanged(NotifyCollectionChangedAction.Reset);
}

You will notice from the above code we don't fire the events to notify observers the collection has changed from inside the critical section - the observers are notified in a sequential manner and therefore doing this inside of the critical section would mean holding the lock for a longer period and we are trying to reduce this time to a minimum.

I mentioned above a way to get around the problem of enumerating the collection whilst another thread makes modifications, we do make use of this pattern, a copy is made for each call to the either of the GetEnumerator methods. We took the view that the collection would never contain 'to many' items that making a copy of the list would be an issue - we don't envisage have 1000's of items, what would be the point on a WP7 device.

The last major issue to consider when implementing the collection was - do we want to support the firing the events on the UI thread via the 'Dispatcher.BeginInvoke' method. We took the view this is not the responibility of the collection, it's the responsibility of the host application to make sure they are on the correct thread (if required). The responsibility of collection is to maintain and update items and notify observers, not to manage any constraints of the UI threading model - Single Responsibility Principle.

The full implementation can be found in the WP7Contrib.Collections project on CodePlex.

Comments

Popular posts from this blog

Implementing a busy indicator using a visual overlay in MVVM

This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whilst it's retrieving or rendering data. Now we could have done this by launching a child dialog window but that feels rather out of date and clumsy, we wanted a more modern pattern similar to the way <div> overlays are done on the web. Imagine we have the following simple WPF app and when 'Click' is pressed a busy waiting overlay is shown for the duration entered into the text box. What I'm interested in here is not the actual UI element of the busy indicator but how I go about getting this to show & hide from when using MVVM. The actual UI elements are the standard Busy Indicator coming from the WPF Toolkit : The XAML behind this window is very simple, the important part is the ViewHost. As you can see the ViewHost uses a ContentPresenter element which is bound to the view model, IMainViewModel, it contains 3 child v...

Showing a message box from a ViewModel in MVVM

I was doing a code review with a client last week for a WPF app using MVVM and they asked ' How can I show a message from the ViewModel? '. What follows is how I would (and have) solved the problem in the past. When I hear the words ' show a message... ' I instantly think you mean show a transient modal message box that requires the user input before continuing ' with something else ' - once the user has interacted with the message box it will disappear. The following solution only applies to this scenario. The first solution is the easiest but is very wrong from a separation perspective. It violates the ideas behind the Model-View-Controller pattern because it places View concerns inside the ViewModel - the ViewModel now knows about the type of the View and specifically it knows how to show a message box window: The second approach addresses this concern by introducing the idea of messaging\events between the ViewModel and the View. In the example ...

WPF tips & tricks: Dispatcher thread performance

Not blogged for an age, and I received an email last week which provoked me back to life. It was a job spec for a WPF contract where they want help sorting out the performance of their app especially around grids and tabular data. I thought I'd shared some tips & tricks I've picked up along the way, these aren't probably going to solve any issues you might be having directly, but they might point you in the right direction when trying to find and resolve performance issues with a WPF app. First off, performance is something you shouldn't try and improve without evidence, and this means having evidence proving you've improved the performance - before & after metrics for example. Without this you're basically pissing into the wind, which can be fun from a developer point of view but bad for a project :) So, what do I mean by ' Dispatcher thread performance '? The 'dispatcher thread' or the 'UI thread' is probably the most ...