2012-03-06 69 views

回答

2

試一下

public class ObservableCollectionThreadSafe<T> : ObservableCollection<T> 
{ 
    // Override the event so this class can access it 
    public override event NotifyCollectionChangedEventHandler CollectionChanged; 

    public ObservableCollectionThreadSafe() 
    { 
    } 

    public ObservableCollectionThreadSafe(IEnumerable<T> items) 
     : base(items) 
    { 
    } 

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) 
    { 
     // Be nice - use BlockReentrancy like MSDN said 
     using (BlockReentrancy()) 
     { 
      NotifyCollectionChangedEventHandler eventHandler = CollectionChanged; 
      if (eventHandler == null) 
       return; 

      Delegate[] delegates = eventHandler.GetInvocationList(); 

      // Walk thru invocation list 
      foreach (NotifyCollectionChangedEventHandler handler in delegates) 
      { 
       DispatcherObject dispatcherObject = handler.Target as DispatcherObject; 

       // If the subscriber is a DispatcherObject and different thread 
       if (dispatcherObject != null && dispatcherObject.CheckAccess() == false) 
       { 
        // Invoke handler in the target dispatcher's thread 
        dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, this, e); 
       } 
       else // Execute handler as is 
        handler(this, e); 
      } 
     } 
    } 
} 

編輯:順便說一下,這不是我的代碼,它是在網絡上被人發現......所以「某人」如果你意識到你自己,你應該把它的信用...

+0

我已經使用了你之前在這裏發佈的代碼,它運行得很好。雖然現在我有另一個項目,我想要做類似的事情,但(出於工作原因)它需要在VB.NET中。 VB似乎並不喜歡像變量一樣使用事件,他說 「Public Shadows Event CollectionChanged(sender As Object,e As System.Collections.Specialized.NotifyCollectionChangedEventArgs)'是一個事件,不能直接調用。 'RaiseEvent'聲明提出一個事件。「 任何想法如何轉換? – JamesMLV 2012-04-19 00:56:38

+0

猜猜我應該google更多。要在VB中完成這項工作(在正常轉換後),您只需在事件名稱後添加「Event」即可。它沒有在智能感知中顯示,但沒有提供任何錯誤和作品。 – JamesMLV 2012-04-19 00:59:46