VB中的多线程ObservableCollection

时间:2010-07-14 20:46:59

标签: wpf vb.net multithreading

这是我尝试在VB中创建一个WPF线程安​​全的ObservableCollection。你能想到它可能遇到的任何问题吗?

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

(通过线程安全,我的意思是安全地使用WPF GUI线程。显然它仍然无法处理并发更新。)

2 个答案:

答案 0 :(得分:2)

也许你可以看看: http://www.codeproject.com/KB/collections/AsyncObservableCollection.aspx 它不是在VB中,而是在C#中,但您可能会找到一些想法。您还应该使用属性“SyncRoot”中的锁定对象。

祝你好运,

埃里克

答案 1 :(得分:0)

不是从observable集合继承,而是包装现有的并发列表并自己实现INotifyCollectionChanged。