Skip to content

Instantly share code, notes, and snippets.

@lummo
Forked from danielmarbach/SafeObservableCollection
Created September 17, 2012 08:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lummo/3736163 to your computer and use it in GitHub Desktop.
Save lummo/3736163 to your computer and use it in GitHub Desktop.
Thread safe observable collection
[DebuggerDisplay("Count = {Count}")]
[ComVisible(false)]
public class SafeObservableCollection<T> : ObservableCollection<T>
{
private readonly Dispatcher dispatcher;
public SafeObservableCollection()
: this(Enumerable.Empty<T>())
{
}
public SafeObservableCollection(Dispatcher dispatcher)
: this(Enumerable.Empty<T>(), dispatcher)
{
}
public SafeObservableCollection(IEnumerable<T> collection)
: this(collection, Dispatcher.CurrentDispatcher)
{
}
public SafeObservableCollection(IEnumerable<T> collection, Dispatcher dispatcher)
{
this.dispatcher = dispatcher;
foreach (T item in collection)
{
this.Add(item);
}
}
protected override void SetItem(int index, T item)
{
this.ExecuteOrInvoke(() => this.SetItemBase(index, item));
}
protected override void MoveItem(int oldIndex, int newIndex)
{
this.ExecuteOrInvoke(() => this.MoveItemBase(oldIndex, newIndex));
}
protected override void ClearItems()
{
this.ExecuteOrInvoke(this.ClearItemsBase);
}
protected override void InsertItem(int index, T item)
{
this.ExecuteOrInvoke(() => this.InsertItemBase(index, item));
}
protected override void RemoveItem(int index)
{
this.ExecuteOrInvoke(() => this.RemoveItemBase(index));
}
private void RemoveItemBase(int index)
{
base.RemoveItem(index);
}
private void InsertItemBase(int index, T item)
{
base.InsertItem(index, item);
}
private void ClearItemsBase()
{
base.ClearItems();
}
private void MoveItemBase(int oldIndex, int newIndex)
{
base.MoveItem(oldIndex, newIndex);
}
private void SetItemBase(int index, T item)
{
base.SetItem(index, item);
}
private void ExecuteOrInvoke(Action action)
{
if (this.dispatcher.CheckAccess())
{
action();
}
else
{
this.dispatcher.Invoke(action);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment