Forked from thomaslevesque/AsyncObservableCollection.cs
Created
February 15, 2016 00:17
-
-
Save ajai8085/695382a5aa7d6a8482f2 to your computer and use it in GitHub Desktop.
This file contains 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.Generic; | |
using System.Collections.ObjectModel; | |
using System.Threading; | |
namespace WpfApplication1 | |
{ | |
public class AsyncObservableCollection<T> : ObservableCollection<T> | |
{ | |
private readonly SynchronizationContext _synchronizationContext = SynchronizationContext.Current; | |
public AsyncObservableCollection() | |
{ | |
} | |
public AsyncObservableCollection(IEnumerable<T> list) | |
: base(list) | |
{ | |
} | |
private void ExecuteOnSyncContext(Action action) | |
{ | |
if (SynchronizationContext.Current == _synchronizationContext) | |
{ | |
action(); | |
} | |
else | |
{ | |
_synchronizationContext.Send(_ => action(), null); | |
} | |
} | |
protected override void InsertItem(int index, T item) | |
{ | |
ExecuteOnSyncContext(() => base.InsertItem(index, item)); | |
} | |
protected override void RemoveItem(int index) | |
{ | |
ExecuteOnSyncContext(() => base.RemoveItem(index)); | |
} | |
protected override void SetItem(int index, T item) | |
{ | |
ExecuteOnSyncContext(() => base.SetItem(index, item)); | |
} | |
protected override void MoveItem(int oldIndex, int newIndex) | |
{ | |
ExecuteOnSyncContext(() => base.MoveItem(oldIndex, newIndex)); | |
} | |
protected override void ClearItems() | |
{ | |
ExecuteOnSyncContext(() => base.ClearItems()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment