Data is not always readily available for applications to display, and it is essential to notify the user when any long running process is going to hinder the smoothness of a user's workflow: it is indeed the least of things as loading time is a purely technical issue. As a rule of thumb, consider any delay superior to a third of a second as an event the user should be notified about.
This post and its associated example project, show two ways to provide users with feedback during a long running operation. The first one uses a wrapper class to load data using the BackgroundWorker, while the other leverages WPF's ObjectDataProvider.
Wrapper with BackgroundWorker
This pattern is made up of a single class implementing INotifyPropertyChanged exposing two properties: IsBusy and Data. The Load method sets the IsBusy property to True and starts up a local BackgroundWorker. When BackgroundWorker.RunWorkerCompleted is fired, property change notifications are called for IsBusy and Data. The simplicity of this wrapper class allows it to be easily extended to include support for finer-grained details using BackgroundWorker.ReportsProgress (which is left as an exercise for the reader ;).
Below is a usage example demonstrating the simplicity of the consuming markup:
First of all, one might at first question the need for a new class as WPF's ObjectDataProvider already features the IsAsynchronous property. But digging a bit deeper uncovers two important issues:
- IsAsynchronous is not a dependency property
- Binding to ObjectDataProviderIsAsynchronous doesn’t work as expected because as ObjectDataProvider derives from DataSourceProvider, any binding to it will reference the resulting data, and not the DataSourceProvider instance itself.
The reporter technique requires two classes: a reporter and a derivation from ObjectDataProvider (which I called IsBusyObjectDataProvider) which will leverage IsAsynchronous for the background operation. IsBusyObjectDataProvider’s IsAsynchronous is forced to true, and its IsBusy property is set to true and false respectively in the BeginQuery and OnQueryFinished overrides. The second class, the reporter, watches for changes in its IsBusyObjectDataProvider.IsBusy, and relays the changes via its own IsBusy property.
The client code has to declare an instance of the reporter:
And then binds data loading logic to the reporter’s child ObjectDataProvider, and UI notification logic to the reporter’s IsBusy property:
Each approach has its pro and cons. The wrapper pattern requires creating a class with some “plumbing” for every kind of load operation, while the reporter one other makes the XAML slightly more verbose, in exchange for improved reusability. Thanks to Christophe Marty for submitting his question about asynchronous loading 🙂
Thanks to Christophe Marty for submitting his question about asynchronous loading 🙂