Related issues have come up in a number of previous questions (see below), but none of the solutions discussed seem to work in this case. The application in question uses an ObservableCollection<T>
to drive a regular WPF ListBox
(with some custom styling) via data-binding. The ObservableCollection may contain a large number of items, but as the ListBox by default operates in a virtualized way, this isn't an issue. ('Static' performance with hundreds of thousands of items is very respectable.)
However, if the collection already contains a large number of items and then a further large number of items is added (via ObservableCollection<T>.Add()
), inevitably the UI grinds to a halt for a while due to all the NotifyCollectionChanged
events being fired. The recommended workaround here is to sub-class the ObservableCollection and implement an AddRange()
method, which adds the new elements to the (protected) Items
collection, and then to call NotifyCollectionChanged
with NotifyCollectionChangedAction.Reset
.
In my experience, this solves one problem, but creates another. Whilst there is no longer a large number of Add
events being raised, the Reset
notification causes the ListBox to reevaluate the whole collection, which if it contains many tens of thousands of items, can take considerable time. This, coupled with the fact that in the target application, large numbers of items may be added frequently, means the application is chewing a lot of CPU for a long time whilst the ListBox digests all the new information.
It's arguable in hindsight that ObservableCollection<T>
was not the right vehicle for offering up such a large dataset to the user, but having come this far, it's hard to see an easy way to rearchitect the app to deal with this issue.
Suggestions gratefully received; many thanks in advance.
Related questions:
- Which .Net collection for adding multiple objects at once and getting notified?
- ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?
- Add/Remove many items to/from a large databound ObservableCollection without freezing the GUI
- Replacement for ObservableCollection?