开发者

Multi-threaded ObservableCollection in VB

开发者 https://www.devze.com 2023-01-07 00:22 出处:网络
This is my attempt to create a ObservableCollection in VB that is WPF thread-safe. Can you think of any problems it may have?

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
                   开发者_JAVA技巧 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.)


Perhaps you could look at: http://www.codeproject.com/KB/collections/AsyncObservableCollection.aspx It's not in VB, it's in C# but you could probably find some ideas. You should also use the locking object from the property "SyncRoot".

Good luck,

Eric


Instead of inheriting from observable collection, wrap an existing concurrent list and implement INotifyCollectionChanged yourself.

0

精彩评论

暂无评论...
验证码 换一张
取 消