views:

43

answers:

2

I have a WPF ListView that is bound to a collection (List<T>). It is currently updated from the current thread which works ok.

I want to move the logic for updating the list into a thread and I see some potential issues regarding thread safety and the binding of the list. Can I be assured that the binding will not be updated unless I call NotifyPropertyChanged? Is NotifyPropertyChanged a blocking call or does it just add it to a message queue; in this instance surely there may be a condition where I tell the ListView the collection updated, but by the time the binding updates I may be modifying the collection in the other thread which will throw an exception or crash the program.

What is the best method for implementing thread safety in such a scenario?

A: 

You can make the collection update from Dispatcher.Invoke to avoid those threading problems:

void ThreadProc()
{
   window.Dispatcher.Invoke(() => {
      //UpdateList
   });
}
gustavogb
Invoke isn't a blocking call though is it? Surely it is then possible for the binding to be updated at the same time the list is modified.
Chris
@Chris It is synchronous, but you can always call Begin/EndInvoke.
Will
+1  A: 

INotifyPropertyChanged is not thread safe, and it does block the calling thread.

Best? That's A good question. I dunno. The bottom line is that, at some time or another, calls must be marshalled onto the UI thread. When do you do this?

You could 1) prepare everything, then deliver it to the UI thread where the UI is then updated. Or, you could 2) implement INotifyPropertyChanged and make the firing of that event always happen on the UI thread, or 3) you could do one of a number of different things.

Usually, however, you would want updates to the UI to happen all at once (not one at a time, as you would get when adding single items to an ObservableCollection, for instance). So it might be advisable to make some thread safe base classes that implement INotifyProperty and CollectionChanged and use these.

There is nothing in the framework that will do this for you, unfortunately.

Will