ObservableCollection
s raise notifications for each action performed on them. Firstly they dont have bulk add or remove calls, secondly they are not thread safe.
Doesn't this make them slower? Cant we have a faster alternative? Some say ICollectionView
wrapped around an ObservableCollection
is fast? How true is this claim.
ObservableCollection
can be fast, if it wants to. :-)The code below is a very good example of a thread safe, faster observable collection and you can extend it further to your wish.
Also
ICollectionView
that sits above theObservableCollection
is actively aware of the changes and performs filtering, grouping, sorting relatively fast as compared to any other source list.Again observable collections may not be a perfect answer for faster data updates but they do their job pretty well.
I can't add comments because I'm not cool enough yet, but sharing this issue I ran into is probably worth posting even though it's not really an answer. I kept getting an "Index was out of range" exception using this FastObservableCollection, because of the BeginInvoke. Apparently changes being notified can be undone before the handler is called, so to fix this I passed the following as the fourth parameter for the BeginInvoke called from the OnCollectionChanged method (as opposed to using the event args one):
Instead of this:
This fixed the "Index was out of range" issue I was running into. Here's a more detailed explaination / code snpipet: Where do I get a thread-safe CollectionView?
An example where is created a synchronized Observable list:
Here is a compilation of some solutions which I made. The idea of collection changed invokation taken from first answer.
Also seems that "Reset" operation should be synchronous with main thread otherwise strange things happen to CollectionView and CollectionViewSource.
I think that's because on "Reset" handler tries to read the collection contents immediately and they should be already in place. If you do "Reset" async and than immediately add some items also async than newly added items might be added twice.