ObservableCollection thread safe in Silverlight
Scritto da
Fadi Scavo il
venerdì 18 novembre 2011
•
Linguaggio:
• Livello: 200
A volte può capitare di dover aggiungere un elemento ad una
ObservableCollection da un thread che non sia quello
proprietario dell'interfaccia. In questo caso, se non adottiamo
l'utilizzo del dispatcher, otteniamo una bella eccezione "Invalid
cross-thread access".
La classe proposta in questa pillola risolve il problema
incapsulando l'utilizzo del dispatcher:
C#
public class DispatcherObservableCollection<T> : ObservableCollection<T>
{
private Dispatcher _dispatcher;
public DispatcherObservableCollection(Dispatcher dispatcher)
{
_dispatcher = dispatcher;
}
protected override void SetItem(int index, T item)
{
InvokeMethod(() => base.SetItem(index, item));
}
protected override void InsertItem(int index, T item)
{
InvokeMethod(() => base.InsertItem(index, item));
}
protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
InvokeMethod(() => base.OnCollectionChanged(e));
}
protected override void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e)
{
InvokeMethod(() => base.OnPropertyChanged(e));
}
private void InvokeMethod(Action action)
{
if (_dispatcher.CheckAccess())
{
action();
}
else
{
_dispatcher.BeginInvoke(action);
}
}
}
Ad esempio:
C#
DispatcherObservableCollection<string> Data = new DispatcherObservableCollection<string>(Deployment.Current.Dispatcher);
Tags: Silverlight