Skip to main content

WP7Contrib: Trickling data to a bound collection

Recently Rich & I've had problems with adding items to list control where the data template is chocked full of XAML goodies - triggers, opacity masks, images, overlay, loads of things I know little about... ;) The culmination of all this UI goodness when used with a bound list control is the blowing of the '90 mb limit' for WP7 devices. As I posted before, we knew the problem wasn't with the data model so we knew it was the data template, now there is plenty of coverage of issues with data templates in Silverlight and this post it not adding to this list, its about a technique to reduce the memory footprint once you've done as much as you can with the data template.

So we're developing an app which exhibits high memory usage, now obviously we want to reduce the memory consumption for the app so we trimmed down the data template for the list control, but we're still seeing the 90 mb limit exceeded for relative few items. Our data set could in theory contain several hundred items but it was failing for less than 40 items and this is an issue.

So Rich can up with the idea of adding a delay between each add to the bound collection - trickle the items, so after some experimentation we discovered the use of a call to the garbage collector when all the items have been added along with a delayed between each item reduced the memory usage to an acceptable level.

The initial implementation Rich came up with used a DispatcherTimer and I thought I could improve on this with Rx (reactive extensions) - this didn't work out (Rich - I won't try and be smart again). Simply the Rx added to much overhead and this caused  the rendering to be less smooth than the DispatcherTimer implementation. So we went back to the DispatcherTimer.

We've provider the implementation in the WP7Contrib, there are currently 2 implementations:

  • TrickleUniqueToCollection<T> - Only adds items not already in the collection,
  • TrickleAllToCollection<T> - adds all items irrespective if they already exist in the collection.

Both classes implement the interface ITrickleToCollection<T> via the base class BaseTrickleToCollection<T>. It defines a set of methods that allow the starting, pausing, resuming and stopping of trickling as required. The start method defined the time delay between each add as well the source collection and the destination collection.

public interface ITrickleToCollection<T>
{
   bool Pending { get; }
   bool IsTrickling { get; }
   void Start(int trickleDelay, IEnumerable<T> sourceCollection, IList<T> destinationCollection);
   void Stop();
   void Suspend();
   void Resume();
}

Both classes use a functional style via the Action method to notify the caller when an action occurs, e.g. when the trickling has started, stopped, item added etc. Shown below is the constructor signatures for both implementations:

public sealed class TrickleUniqueToCollection<T> : BaseTrickleToCollection<T>
{
   public TrickleUniqueToCollection(Action addedAction, Action completedAction)
      : this (addedAction, () => {}, () => {}, () => {}, () => {}, completedAction)

   public TrickleUniqueToCollection(Action addedAction, Action startedAction, Action stoppedAction,
                                    Action suspendedAction, Action resumedAction, Action completedAction)
   : base (addedAction, startedAction, stoppedAction, suspendedAction, resumedAction, completedAction)
}

public sealed class TrickleAllToCollection<T> : BaseTrickleToCollection<T>
{
   public TrickleAllToCollection(Action addedAction, Action completedAction)
      : this (addedAction, () => {}, () => {}, () => {}, () => {}, completedAction)

   public TrickleUniqueToCollection(Action addedAction, Action startedAction, Action stoppedAction,
                                    Action suspendedAction, Action resumedAction, Action completedAction)
   : base (addedAction, startedAction, stoppedAction, suspendedAction, resumedAction, completedAction)
}

Each class has a specific implementation for the DispatcherTimer, shown below is the implementation for the TrickleAllToCollection<T>, the interesting detail is the timer being shutdown once trickling all of the items has completed - no point leaving it running consuming device resources (memory & CPU).

public TrickleAllToCollection(Action addedAction, Action startedAction, Action stoppedAction,
                              Action suspendedAction, Action resumedAction, Action completedAction)
   : base (addedAction, startedAction, stoppedAction, suspendedAction, resumedAction, completedAction)
{
      this.DispatcherTimer = new DispatcherTimer();
      this.DispatcherTimer.Interval = this.StartupDelay;
      this.DispatcherTimer.Tick += delegate
         {
            if (this.DispatcherTimer.IsEnabled)
            {
               if (this.Source.Count != 0)
               {
                  var item = this.Source.Dequeue();
                  this.Destination.Add(item);
                  this.AddedAction();
                                                         
                  if (this.Count == 0)
                     this.DispatcherTimer.Interval = this.Delay;

               this.Count++;
               }
               else
               {
                  this.DispatcherTimer.Stop();
                     this.CompletedAction();
               }
            }
         };
   }

Using these classes is simply, just instantiate an instance with the required Action methods:

 this.trickler = new TrickleUniqueToCollection<Property>(() => this.UpdateTrickleStatus(TrickleStatus.Added),
                                                         () => this.UpdateTrickleStatus(TrickleStatus.Started),
                                                         () => this.UpdateTrickleStatus(TrickleStatus.Stopped),
                                                         () => this.UpdateTrickleStatus(TrickleStatus.Suspended),
                                                         () => this.UpdateTrickleStatus(TrickleStatus.Resumed),
                                                         () => this.UpdateTrickleStatus(TrickleStatus.Completed));

And then start trickling to the bound destination collection:


   this.trickler.Start(432, result.Properties, this.aggregatedPropertiesView);

That's pretty much it, as I said these are in the WP7Contrib and can be found in the Collections project. I've also created a demo application 'TrickleDemo' in the Spikes directory of the code base. This demo doesn't show any memory problems with data templates, it only demonstrates how to use this trickle to collection pattern.

Next time a post about how we do RESTful communication in WP7 using the HttpWebRequest  & Reactive Extensions...

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 ...