Last active
January 10, 2020 01:49
-
-
Save Clancey/1d5d8d02b28442e16a9cbd272403d04c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.ObjectModel; | |
using System.Linq; | |
using System.Collections.Specialized; | |
using System.Timers; | |
namespace System.Collections.Generic { | |
public class BulkUpdateObservableCollection<T> : ObservableCollection<T> { | |
bool isBulkUpdating; | |
protected override void OnCollectionChanged (NotifyCollectionChangedEventArgs e) | |
{ | |
if (!isBulkUpdating) | |
base.OnCollectionChanged (e); | |
} | |
Timer searchTimer; | |
List<T> batchItems = new List<T> (); | |
public void AddBatch (T item) | |
{ | |
lock (batchItems) | |
batchItems.Add (item); | |
if (searchTimer == null) { | |
searchTimer = new Timer (100); | |
searchTimer.Elapsed += (s, e) => { | |
lock (batchItems) { | |
var items = batchItems.ToList (); | |
batchItems.Clear (); | |
AddRange (items); | |
} | |
}; | |
} else | |
searchTimer.Stop (); | |
searchTimer.Start (); | |
} | |
public void Replace (IEnumerable<T> items) | |
{ | |
if (!items?.Any () ?? false) { | |
Clear (); | |
return; | |
} | |
isBulkUpdating = true; | |
Clear (); | |
foreach (var item in items) | |
Add (item); | |
isBulkUpdating = false; | |
OnCollectionChanged (new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Reset)); | |
} | |
public void AddRange (IEnumerable<T> items) | |
{ | |
if (!items?.Any () ?? false) { | |
return; | |
} | |
isBulkUpdating = true; | |
var startingIndex = items.Count (); | |
foreach (var item in items) | |
Add (item); | |
isBulkUpdating = false; | |
OnCollectionChanged (new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Add, items.ToList ())); | |
} | |
public void Remove (IEnumerable<T> items) | |
{ | |
if (!items?.Any () ?? false) { | |
return; | |
} | |
isBulkUpdating = true; | |
var startingIndex = items.Count (); | |
foreach (var item in items) | |
Remove (item); | |
isBulkUpdating = false; | |
OnCollectionChanged (new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Remove, items.ToList ())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment