开发者

Thread safety, lists, binding and WPF

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 开发者_C百科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?


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.


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

void ThreadProc()
{
   window.Dispatcher.Invoke(() => {
      //UpdateList
   });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜