Delay Binding Updates within a certain Context

by Damon Payne 16. March 2011 14:16

This came up on Twitter today and since I have a solution that's been working well for me I opted to share. When making a series of data changes that will update Bindings, How can you keep a WPF/Silverlight UI from reflecting any of these changes until you're all done?  In other words, we need the ability to treat a series of Property changes as a single unit of work.

While this works better with the design patterns from my series "Great Features for MVVM Friendly Objects" I will define a more general mechanism here.

Step 1 - Define a mechanism for not firing PropertyChanged

The first step is to give your data objects a means of not firing updates.  We'll create a simple base class here to demonstrate the principles.

public class SampleDataObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Don't fire updates!
        /// </summary>
        public bool SuspendChangeNotification { get; set; }

        protected void OnPropertyChanged(string propName)
        {
            if (null != PropertyChanged && !SuspendChangeNotification)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }
    }

 

Step 2 - Define Reasonable Programming Semantics for Context Boundaries

Whenever I'm solving a problem I always think about the Developer Experience.  Is this going to be so annoying or hard to use that people will seek reasons to avoid using it?  Since we want to define a context with a clear beginning and end I like to see if the problem can be expressed with using() semantics.  It turns out that this one can be.  We'll create an object that does the work we need to do and implements IDisposable so it can be used in a using() {} block:

public class SuspendChangeNotifyContext: IDisposable
    {
        public SuspendChangeNotifyContext(ISupportInitialize target) : this(new List<ISupportInitialize>{target})
        {
        }

        public SuspendChangeNotifyContext(IEnumerable<ISupportInitialize> targets)
        {
            _targets = targets;
            foreach (var t in _targets)
            {
                t.BeginInit();
            }
        }

        IEnumerable<ISupportInitialize> _targets;

        public void Dispose()
        {
            foreach (var t in _targets)
            {
                t.EndInit();
            }
        }
    }

 

This means that our SampleDataObject needs to implement ISupportInitialize, which causes us to implement methods for BeginInit() and EndInit().  I chose this because this interface is already in the Silverlight libraries.  You could certainly make your own interface that looks directly at some other property or methods.

    public class SampleDataObject : INotifyPropertyChangedISupportInitialize
    {
        public event PropertyChangedEventHandler PropertyChanged;
 
        /// <summary>
        /// Don't fire updates!
        /// </summary>
        public bool SuspendChangeNotification { getset; }
 
        protected void OnPropertyChanged(string propName)
        {
            if (null != PropertyChanged && !SuspendChangeNotification)
            {
                PropertyChanged(thisnew PropertyChangedEventArgs(propName));
            }
        }
 
        public void BeginInit()
        {
            SuspendChangeNotification = true;
        }
 
        public void EndInit()
        {
            SuspendChangeNotification = false;
        }
    }

 

Now that we have all of this, we can write reasonable looking code like the following:

            var dataObject = new SampleDataObject();
            using (var ctx = new SuspendChangeNotifyContext(new List<ISupportInitialize> { dataObject }))
            {
                //make Property changes here!
            }

That's an extremely reasonable looking way to accomplish our goal, but we're not quite done yet.

Step 3 - Done Making Changes

Of course, what's missing from the above example is that after we're done, we want to notify the UI all at once about the changes we made during the SuspendChangeNotify batch.  Given what we already have that is extremely easy to do.  We can keep track of which properties changed and fire Notification for them all from EndInit().

    public class SampleDataObject : INotifyPropertyChangedISupportInitialize
    {
        public event PropertyChangedEventHandler PropertyChanged;
 
        List<string> _batchChanges;
 
        /// <summary>
        /// Don't fire updates!
        /// </summary>
        public bool SuspendChangeNotification { getset; }
 
        protected void OnPropertyChanged(string propName)
        {
            if (SuspendChangeNotification)
            {
                if (!_batchChanges.Contains(propName))
                {
                    _batchChanges.Add(propName);
                }
            }
            else if (null != PropertyChanged)
            {
                PropertyChanged(thisnew PropertyChangedEventArgs(propName));
            }
        }
 
        public void BeginInit()
        {
            SuspendChangeNotification = true;
            _batchChanges = new List<string>();
        }
 
        public void EndInit()
        {
            SuspendChangeNotification = false;
            foreach (string propName in _batchChanges)
            {
                OnPropertyChanged(propName);
            }
            _batchChanges = null;
        }
    }

Because we've done this with using() blocks this is a fairly safe way to accomplish this without concerns that the data objects will get "wedged" if an exception is thrown.

A Final Note on Design

The approach shown here, works but might appear a little untidy.  If you check out my (ongoing) series on Great Features for MVVM Friendly Objects you can see a means of an elegant repackaging of what's shown here.  This is especially true of the change-tracking portion of the code.

Enjoy!

Tags:

Architecture and Design | Silverlight | WPF

MEF for Windows Phone 7

by Damon Payne 1. March 2011 17:45

I wrote a while back about my port of MEF to Windows Phone 7, and apprently didn't make a binary available as I've been getting email and twitter requests for it.

Download it here.

See the original article for detailed notes.  The big points are that dynamic export metadata won't work due to not having Reflection Emit on WP7 and that DeploymentCatalog doesn't really make sense so I excluded System.ComponentModel.Composition.Initialization -  use AssemblyCatalogs instead.

I will be maintaining this so please report any issues.

Why is this not part of MEF Contrib?  Mostly due to some timing issues last year and my own GitHub issues.

Tags:

Silverlight | Windows Phone 7 Development | WindowsPhone7 | MEF

Edgenet Partners with Search Giant Bing

by Damon Payne 16. February 2011 15:48

Another press release for last year's big project!

http://www.edgenet.com/index.php/bing-webinar/bing-webinar.html

"We're proud to announce a new partnership with the search giant Bing. Bing highly values the quality and features of the data we provide, and we welcome their partnership as we continue to enhance your web presence."

Check it out.

Tags:

Silverlight | Technical Community

Upcoming Speaking Engagements

by Damon Payne 13. February 2011 19:38

Well, I didn’t get to speak at MIX 2011 as neither of my Open Call submissions got enough votes.  However, there are some most excellent closer-to-home venues I’ll be presenting at in the not to distant future:

Deeper in .NET 2011

http://www.wi-ineta.org/DesktopDefault.aspx?tabid=203

Well, it’s been a couple of years, but Milwaukee is going to have an awesome code camp again. This is going to be an awesome event with Mads Kristensen, Jay Schmelzer, Joe Stagner, Rocky Lhotka and.. me!  (Me?)How I get to take the stage next to giants like these guys remains a mystery but I have to thank the organizers for making room for a home-town presenter. 

 

Fox Valley Day of .NET

http://dayofdotnet.fvnug.org/

I think this will be my third year in a row speaking at this event.  Wow am I getting old.  The guys in the Fox Valley have really created a fantastic community up there.  The Fox Valley guys are cutting edge, busy, and bigger than most people down in the Metro Milwaukee area realize.  Not only is this a great event every year but they take great care of the speakers.  <Beer/>  I'm definitely looking forward to this event. 

It’s too bad that, at this event, I’m going to have to make some tough decisions.  My compatriots from the Madison area, Lance Larsen and Travis Feirtag, are both giving great talks at the same time.  I can’t see Scott Seely’s talk because he’s in the same slot as me.  Maybe we can get the guys to record the sessions this year?

Tags:

Silverlight | Technical Community | Architecture and Design

Binary Drop For the Task Parallel Library for Silverlight

by Damon Payne 13. February 2011 18:45

Since there was interest, I am doing a binary drop of my port of the Task Parallel Library for Silverlight 4.  Please contact me with feedback, bugs, and suggestions.  Once I’m done with some more performance–centric unit tests I will post the source code as well.  I’d like to have something set up that shows this off within a Silverlight app.

Download the binaries here.

Tags:

Silverlight | Parallel

Task Parallel Library Ported to Silverlight 4

by Damon Payne 7. February 2011 19:02

Long time readers will recall that I’ve done some oddball parallel articles over the years.  I recently decided to challenge myself with porting the Task Parallel Library to Silverlight 4.  The port is complete and all unit tests pass.  I’m still profiling but I’m generally encouraged by the results.

Why?

A fair question.  Why do I need libraries for making it easier to write multithreaded code in Silverlight? 

First, Silverlight is making big strides as a platform for Business applications.   Business applications might be able to absorb extra computing power on the client machine.  I envision data analysis applications doing lots of work on the client PC.  Silverlight Games might be another case when you are doing a lot of game-world updating or computations yourself.  What about popular distributed computing applications like Folding @Home or SETI? 

Then, of course, there’s the fact that we find ourselves doing minor threading work on Silverlight applications already today.  For example, at work I have a Silverlight application which imports data from very large Excel files on background threads.  The fact is that the Task model, the Cancellation Token model, and the Concurrent Data Structures are just really nice programming models.

Comments on the TPL Port, and Porting in General

I didn’t start from scratch.  The Mono Project has been working on an implementation for their .NET 4 stack.  Most of the credit, then, goes to Jérémie "Garuma" Laval.  I grabbed all of System, System.Collections.Concurrent, System.Collections.Concurrent.Partitioners, System.Threading, and System.Threading.Tasks and brought things in one class at a time as I needed them to get System.Threading.Tasks to compile.

Some comments on the port:

  • Serializable –  A good example of something that’s missing from Silverlight.  I find that I tend not to comment these things out but rather make an attribute that does nothing.  If Silverlight supports this in the future or I discover something useful I could do the mock version is nice.
  • No Thread.Yield in Silverlight – I was worried things like this being missing would kill this port.  After doing some research, replacing these with Thread.Sleep(0) should have the desired effect.
  • No Interlocked.Read in Silverlight – I’m most worried by this omission.  Interlocked.Read allows you to do atomic operations on long integers in a 32bit process, which Silverlight always is until Silverlight 5.  I don’t have pointers or any other workarounds that I could think of either.  This means in the work-stealing portions of the Queues that parallel tasks use I have some operations that need to be atomic but aren’t.   I may go back and change these to 32bit integers.  No one wants to wait on a long integer’s worth of Tasks anyway. 
  •  No Thread priority in SIlverlight- The task parallel library portions that dealt with thread priority had to be #-defined out.
  • Array.Convert() – Missing from Silverlight, but easy to re-create as an extension method.

Performance and Source Code

I am doing some profiling to see if there’s anything I can do to increase performance.  Running the same unit tests on this port and the full .NET framework has revealed that this code isn’t as fast on Silverlight.  Still, as I said I think having this programming model is pretty nice even without perfectly linear per-core speedups. 

I will release the source code if there’s interest.  I believe the Mono license allows me to do this as long as I leave their license in tact in the the source files.  I should definitely head out to user voice and ask for some of these features in a future version of Silverlight.

Tags:

Silverlight | Parallel

Vote for my MIX2011 Sessions

by Damon Payne 25. January 2011 14:12

My proposals for MIX 2011 have made the initial cut and are on the MIX Open Call site for voting!  Even if you're not going to MIX, head over to http://live.visitmix.com/OpenCall and vote on what sounds interesting.

You can read about my proposals at:

Advanced MVVM Techniques for Silverlight Business Applications http://live.visitmix.com/OpenCall/Vote/Session/130

WCF Patterns and Practices for Silverlight http://live.visitmix.com/OpenCall/Vote/Session/131

Wish me luck! 

Tags:

Silverlight | Technical Community

Google Merchant Blog Mentions Edgenet

by Damon Payne 10. January 2011 11:31

The Google Merchant Blog mentiones my project directly:

http://googlemerchantblog.blogspot.com/2011/01/going-to-source-to-improve-product-data.html

We are starting this effort through a business partnership with Edgenet, a provider of product data management solutions. Manufacturers and suppliers can work directly with Edgenet's Ezeedata service to submit high-quality product data and images to Google. For more information, you can visit their website, at www.edgenet.com.

This is the gigantic Silverlight/WCF effor I mentioned before.

{Edit: this post puts us on the "Google Acquisition Watch List" http://searchengineland.com/google-partner-brings-big-data-to-product-search-60711 }

Tags:

Migrated to blogengine.net

by Damon Payne 2. January 2011 20:44

This is a test post!

Hopefully this example post down here works and looks super duper!

http://www.damonpayne.com/2010/06/17/GreatFeaturesForMVVMFriendlyObjectsPart0FavorCompositionOverInheritance.aspx 

Tags:

Blog | BlogEngine.NET

PDC Local 2010 Code and Slides

by Administrator 7. November 2010 20:26

The recent PDC local event was a lot of fun this past Friday.  Clark Sell spoke about “Fun with Visual Studio 2010”, I spoke on putting the finishing touches on your Windows Phone 7 application, and Scott Seely ended the day with a very technical look into some new Windows Azure features announced recently at PDC.

My source code includes some useful items such as a basic Command Binding implementation for Windows Phone 7. 

Download the code and slides here.

Tags:

About the author

Damon Payne is a Microsoft MVP specializing in Smart Client solution architecture. 

INETA Community Speakers Program

Month List

Page List

flickr photostream