Accessing ViewModel properties from separate thread

前端 未结 3 1806
庸人自扰
庸人自扰 2021-01-03 00:52

In my wpf application, a time consuming operation in my viewmodel is called using a separate thread. This function, however, accesses several properties in the viewmodel tha

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 01:21

    If you use extend your ObservableCollection with this, you can update from a separate thread:

    /// 
    /// Source: New Things I Learned
    /// Title: Have worker thread update ObservableCollection that is bound to a ListCollectionView
    /// http://geekswithblogs.net/NewThingsILearned/archive/2008/01/16/have-worker-thread-update-observablecollection-that-is-bound-to-a.aspx
    /// Note: Improved for clarity and the following of proper coding standards.
    /// 
    /// 
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        // Use BlockReentrancy
        using (BlockReentrancy())
        {
            var eventHandler = CollectionChanged;
    
            // Only proceed if handler exists.
            if (eventHandler != null)
            {
                Delegate[] delegates = eventHandler.GetInvocationList();
    
                // Walk thru invocation list
                foreach (NotifyCollectionChangedEventHandler handler in delegates)
                {
                    var currentDispatcher = handler.Target as DispatcherObject;
    
                    // If the subscriber is a DispatcherObject and different thread
                    if ((currentDispatcher != null) &&
                        (currentDispatcher.CheckAccess() == false))
                    {
                        // Invoke handler in the target dispatcher's thread
                        currentDispatcher.Dispatcher.Invoke(
                            DispatcherPriority.DataBind, handler, this, e);
                    }
    
                    else
                    {
                        handler(this, e);
                    }
                }
            }
        }
    }
    
    /// 
    /// Overridden NotifyCollectionChangedEventHandler event.
    /// 
    public override event NotifyCollectionChangedEventHandler CollectionChanged;
    

提交回复
热议问题