Can not operate ObservableCollection in multi threads

前端 未结 4 602
说谎
说谎 2020-12-31 21:44

It seems the ObservableCollection only support add, remove, clear operation from the UI thread, It throw Not Support Exception if it is operated by a NO UI thread. I tried t

4条回答
  •  天涯浪人
    2020-12-31 22:19

    You might want to investigate my answer to this perhaps -but please note that the code came from here and cannot be credited to me. Though I tried to implement it in VB. : Original Site

    I've used this to populate a WPF listbox from a class that has an ObservableCollectionEx populated asynchronously from an access database. It does work.

    public class ObservableCollectionEx : ObservableCollection
    {
       // Override the event so this class can access it
       public override event System.Collections.Specialized.NotifyCollectionChangedEventHandler    
     CollectionChanged;
    
       protected override void OnCollectionChanged    (System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
       {
      // Be nice - use BlockReentrancy like MSDN said
      using (BlockReentrancy())
      {
         System.Collections.Specialized.NotifyCollectionChangedEventHandler eventHandler = CollectionChanged;
         if (eventHandler == null)
            return;
    
         Delegate[] delegates = eventHandler.GetInvocationList();
         // Walk thru invocation list
         foreach (System.Collections.Specialized.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);
         }
      }
    }
    }
    

提交回复
热议问题