views:

145

answers:

2

I seem to be going round in circles.

I have a WPF application that has a main ribbon window with a status bar. When you navigate to a "view" a user control is displayed as the content of the main window.

The view has a ViewModel which handles retrieving data from the database and the View's datacontext is set to the ViewModel.

What I want is to have the lengthy operation (data retrieval) run on a background thread and whilst it is running the status in the main window to report appropriately. When the background task is complete, the status should revert back to "Ready" (much the same as Visual Studio).

How should I wire this together so that I can have the data access code separated out in the ViewModel whilst keeping a responsive UI?

I have tried using the BackgroundWorker is various places in the code and I still end up with an unresponsive UI.

A: 

You can bind a textblock (progressbar) to a dependency property. Then do your stuff in a separate thread and update the dependency property according to the progress. Don'T forget that you have to do this in the correct thread, so store a dispatcher.

Sascha
+1  A: 

I find BackgroundWorker's interface inconvenient for this purpose so I prefer to stick to using ThreadPool directly.

Here's the basic idea:

public class MyViewModel
{
  public SomeCollectionType<Widget> Widgets
  {
    get
    {
      if(!WidgetFillQueued)
      {
        WidgetFillQueued = true;
        ThreadPool.QueueUserWorkItem(_ =>
        {
          WidgetLoadStatus = 0;
          int totalCount = FetchWidgetCount();
          while(_internalWidgetCollection.Count < totalCount && !AbortFill)
          {
            _internalWidgetCollection.AddRange(FetchMoreWidgets());
            WidgetLoadStatus = (double)_internalWidgetCollection.Count / totalCount;
          }
          WidgetLoadStatus = null;  // To indicate complete
        });
      }
      return _internalWidgetCollection;
    }
  }

}

Assuming WidgetLoadStatus is a DependencyProperty that is bound from the UI, WPF's binding system takes care of the thread transitions required to keep the status bar progress display updated.

Assuming _internalWidgetCollection allows multi-threaded access and implements INotifyPropertyChanged properly, all collection updates will also result in UI updates on the UI thread.

In my actual view models there are many collections so instead of using individual properties like WidgetFillQueued and WidgetLoadStatus, I use a data structure that keeps track of all currently executing operations and computes a combined status value for display. But the above code gives the basic idea of how the threading can be implemented properly.

The above is also applicable to loading a single large object such as a file download: Instead of calling AddRange() every time, just accumulate the data until it is all downloaded, then set the property containing the data. Note that if the object itself includes DispatcherObjects it must be deserialized on the UI thread. Do this by calling Dispatcher.BeginInvoke from within the thread.

Ray Burns
Thank you, this sounds like the kind of information I need. I am in the middle of something else at the moment but will try this out in the next couple of days
David Ward