This is my attempt to create a ObservableCollection in VB that is WPF thread-safe. Can you think of any problems it may have?
Public Class WpfObservableCollection(Of T)
Inherits ObjectModel.ObservableCollection(Of T)
Public Sub New()
End Sub
Public Sub New(ByVal list As List(Of T))
MyBase.New(list)
End Sub
Public Sub New(ByVal collection As IEnumerable(Of T))
MyBase.New(collection)
End Sub
Protected Overrides Sub OnCollectionChanged(ByVal e As System.Collections.Specialized.NotifyCollectionChangedEventArgs)
Dim eventList = CType(CollectionChangedField.GetValue(Me), NotifyCollectionChangedEventHandler)
If eventList IsNot Nothing Then
Using Me.BlockReentrancy
Dim activeDispatcher = (From nh In eventList.GetInvocationList() Let dpo = TryCast(nh.Target, DispatcherObject) Where dpo IsNot Nothing Select dpo.Dispatcher).FirstOrDefault()
If activeDispatcher IsNot Nothing AndAlso Not activeDispatcher.CheckAccess Then
activeDispatcher.BeginInvoke(Sub() MyBase.OnCollectionChanged(e), DispatcherPriority.DataBind)
Else
MyBase.OnCollectionChanged(e)
End If
End Using
End If
End Sub
Private Shared ReadOnly CollectionChangedField As FieldInfo = GetType(ObjectModel.ObservableCollection(Of T)).GetField("CollectionChanged", BindingFlags.NonPublic Or BindingFlags.Instance)
End Class
(By thread-safe I mean safe for use with WPF GUI Threads. Obviously it still can't handle concurrent updates.)