The setup of the solution is a little bit complicated and restricts my options.
- There is a project that contains all the GUI components; in it resides a control that contains a list of ‘Project’ items that each contains a list of ‘Document’ items. Initially both of these lists were implemented as ObservableCollections.
- Project and Document are defined in a separate project, one that does not have access to System.Windows
- One of the critical functions of the program generates a Document within a background thread (because it is slow and time-consuming); this Document needs to be added to a Project’s Documents collection.
Since the document is being generated in a background thread, that thread cannot add the document to the collection – a NotSupportedException is generated.
There are several ways to extend ObservableCollections to be thread-safe – unfortunately all of the ones that I have seen so far rely on System.Windows.Threading.Dispatcher, which I cannot use due to (2).
I have discovered that I cannot use INotifyPropertyChanged on a list and must use a collection implementing INotifyCollectionChanged – basically ObservableCollection again. I’m not sure if it’s a good idea to implement an extension of a List object when there are so many different methods that modify it, and what’s to say it wouldn’t have the same issues as ObservableCollection?
Using an explicit UpdateSourceTrigger on the binding does not look feasible, given that the Document is in a HierarchicalDataTemplate, and in any case passing the binding to the Project object looks to be a bit ugly.
Any suggestions?
Create the document on the background thread but use a callback on the primary thread to add it to the ObservableCollection (assuming the ObservableCollection is created on the primary thread).