views:

16

answers:

1

This may be seen as a duplicate of http://stackoverflow.com/questions/3423248/thread-safety-lists-binding-and-wpf, but I post it anyway since I'm not fully happy with the accepted response, and I might be able to express what I suspect is the same question more exactly.

Any operations related to UI in WPF/Silverlight must be performed on the UI, including INotifyPropertyChanged and INotifyCollectionChanged, but - when data binding to an object (single object or collection), will the framework only read the values of the data bound object synchronously in the event handler, or could it come back any time and query the object?

What I want to do is have a worker thread updating a data bound object (often), periodically raising a CollectionChanged event if the collection is dirty to trigger a UI update. If I can know that the framework will only read the values in the collection in the event handler, a simple lock in the code raising the event to lock the collection would be enough, but if not, I will have to perform a deep copy of the collection.

So 1) can the framework read my collection even outside of the event handler and 2) if it can, is there a better way of updating something on a worker thread and publish it to the UI other than performing a deep copy?

A: 

Hi!

You can´t guarantee that something will only read your structure in the event handler since the databinding could be refreshed if any other window controls causes a refresh on the hiearchy so locking the structure isn't what I would do.

As mentioned in the post you´ve found the way to do this is to make sure that the event is posted to the GUI-thread in a safe manner using the dispatcher like below:

public void DoWork(object sender, DoWorkEventArgs e)
{
    // Update GUI
    Dispatcher.BeginInvoke(new Action(MyPostMethod), DispatcherPriority.Normal);
}

public void MyPostMethod()
{
    // Here you´d post whatever data to the gui
}

I usually use the Action and Action<T> constructs to not having to create new delegates for every to-gui posting.

Almund