WPF ObservableCollection – Add millions of data within milliseconds

Adding huge amount of Data to an ObservableCollection can cause GUI freezes. Even if operating on another thread, the process of adding items is pretty slow. But why?

Every time an Item gets added to the ObservableCollection, some OnPropertyChanged methods will be called. Therefore, every listener will receive an update, which results in a huge overhead.

To avoid this problem, we implement your own ObservableCollection which truly just adds all the elements without throwing a single OnPropertyChanged event. Only after the whole insertion is done, we call the PropertyChanged events.

/// <summary>
/// SilentObservableCollection is a ObservableCollection with some extensions.
/// </summary>
/// <typeparam name="T"></typeparam>
public class SilentObservableCollection < T > :ObservableCollection < T > {
	/// <summary>
	/// Adds a range of items to the observable collection.
	/// Instead of iterating through all elements and adding them
	/// one by one (which causes OnPropertyChanged events), all
	/// the items gets added instantly without firing events.
	/// After adding all elements, the OnPropertyChanged event will be fired.
	/// </summary>
	/// <param name="enumerable"></param>
	public void AddRange(IEnumerable < T > enumerable) {
		CheckReentrancy();

		int startIndex = Count;

		foreach(var item in enumerable)
		Items.Add(item);

		OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new List < T > (enumerable), startIndex));
		OnPropertyChanged(new PropertyChangedEventArgs("Count"));
		OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
	}
}
5 1 vote
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments