2010-07-14 66 views
2

這是我嘗試在VB中創建一個WPF線程安​​全的ObservableCollection。你能想到它可能存在的任何問題嗎?VB中的多線程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線程使用安全顯然,這仍然不能處理併發更新)

+0

我很好奇,爲什麼當你已經有一個新的(IEnumerable(Of T))時,你提供了一個New(List(Of T))。任何原因? – 2011-01-17 05:12:43

回答

0

而是從觀察的集合繼承的,包裝已有併發名單和執行INotifyCollectionChanged自己。