6

Right, sticking with the MVVM focus for the minute, there are a small number of scenarios where threading may occur:

As usual, for simplicity we have a Model class, ViewModel class and View class. The Model has a Collection and a string property.

1) User triggers long running background task. View triggers ViewModel. Can easily be managed by ViewModel using, for example, BackgroundWorker

2) Thread updates Model, ViewModel notified by Model of changes.

Previously we've discussed using INotifyChanged to notify changes from Model to ViewModel. The DependencyProperty system appears to marshal these to the correct thread for you.

For ObservableCollections this does not work. Therefore should my model's public face be single threaded (Don't like, why should the Model know about threads) or would I replicate some parts of the Model (For example the Collection above) in the ViewModel to ensure that amendments are made on the correct thread?

I think I've sort of answered my own question. Perhaps not. My Model does know about threads, so perhaps it's only polite to markshal them back using the IMarshalInvoker idea mooted earlier by Colin?

Some of my problem here is that I consider MVVM to be yet another MVC variant, and historically I've been happy to use terms like MVP, MP, MVC pretty much interchangeably because I knew what worked with the GUI technology (usually winforms) on the V end. When I say MVVM I'm specifically looking for practical advice on what works for WPF and WPF specific foibles. I hope that explains the nature of my questions and why I'm asking them.

Jon
  • 428,835
  • 81
  • 738
  • 806
Ian
  • 4,885
  • 4
  • 43
  • 65

1 Answers1

6

I don't think it's a very good idea to go all-out and implement collections in your Model as ObservableCollection, as this is "polluting" your Model in a way that's only useful to WPF.

INotifyPropertyChanged is OK because:

  • There are many scenarios where having the ability to "listen in" is useful.
  • It can be utilized from pretty much any .NET code, not just WPF.
  • It doesn't give you any trouble if you want to serialize your Model.

So, I suggest to not have your model know about threads. Make your ViewModel know about threads, like this:

class Model {
    List<Widget> Widgets { get; private set; }
}

class ModelViewModel {
    ObservableCollection<Widget> Widgets { get; private set; }

    ModelViewModel(Model model) {
        this.Widgets = new ObservableCollection<Widget>(model.Widgets);
    }
}

If Widget is a reference type and implements INotifyPropertyChanged (which would be about 100% of the time), this gets you most of the way:

  • Changes to any widget will be made to model itself and will reflect upon bindings immediately
  • Updates to the collection will reflect upon bindings immediately

There's still the problem that updates to the collection (adding and removing items) will not be made to model directly. But that can be arranged:

ModelViewModel(Model model) {
    this.Widgets = new ObservableCollection<Widget>(model.Widgets);
    this.Widgets.CollectionChanged += this.PropagateChangesToModel;
}

void PropagateChangesToModel(object sender, NotifyCollectionChangedEventArgs e) {
    // do what the name says :)
}

Finally, you need to make ObservableCollection play well with being updated from a worker thread. This is a really common issue with WPF, and I refer you to the answer to this question for a solution: ObservableCollection and threading.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Ok, I think I understand what you're saying, so let me give you a little scenario and could you describe how the above fits it? I'll try not to enforce my idea of a solution on it. So we have the Model above and a ModelViewModel (The ViewModel of the Model). I have a component that is listening for news about new widgets and when it gets news it raises an event on its own thread (i.e. not the UI thread). Where do I wire in that component? It sounds like Model material to me, but from the above we're going ViewModel? – Ian Jan 05 '11 at 14:46
  • @Ian: if the component is part of your business logic, then you can either put the hooks in `Model` as you suggest or have a "service" in your app that acts as a `Model` repository. In this case it would have CRUD methods for `Model`s, so when you want to add a `Widget` you would call `UpdateModel(model)` on the service, and the service would fire off a `ModelUpdated` event which components would hook (this approach is Prism-flavored). Can't say which would be preferable for your specific scenario. – Jon Jan 05 '11 at 14:54
  • Ok, and so in that example the ViewModel would subscribe to ModelUpdated, and regardless of what thread it was fired on marshal it back to the correct thread? Historically I'd have a central message bus affair which all components would use to communicate. So my Model might get a new Widget and then generate a new widget message onto the bus which would be consumed by the UI. That's sort of where I'm going I think. Prism I've used but I'm not confident I can extrapolate my understanding to it, I'll go build a new Prism test app :) Thanks – Ian Jan 05 '11 at 15:09
  • @Ian: the ViewModel wouldn't need to marshal anything probably. Even if it decided that the updated Model data should overwrite everything that the user is working on, it could simply replace the `ObservableCollection` it exposes with a new collection. This does not run into the "modify an existing observable collection" problem, so no special threading code would be necessary. – Jon Jan 05 '11 at 15:18
  • Just found a diagram showing MVVM with an additional Controller class which is pretty much what I'd have put together in the first place I think :) – Ian Jan 05 '11 at 15:19