Search code examples
wpfmultithreadingobservablecollectiondispatch

WPF clear ObservableCollection in another thread


I have application in WPF and I want to clear ObservableCollection when setter is set from another thread.

This is setter:

public List<Model.MasterReview> SelectedMasterReviews
        {
            get { return selectedMasterReviews; }
            set
            {
                selectedChildReview = null;
                selectedMasterReviews = value;

                Application.Current.Dispatcher.Invoke((Action)delegate
                {
                    GetChildReviews();
                });
            }
        }


private void GetChildReviews()
        {
            Application.Current.Dispatcher.Invoke((Action)delegate
            {
                ChildReviews.Clear();
            });
}

And I get error:

    This type of CollectionView does not support changes to its SourceCollection from a thread
 different from the Dispatcher thread

This code give me the same error:

var uiContext = SynchronizationContext.Current;
uiContext.Send(x => ChildReviews.Clear(), null);

Solution

  • I've resolve this problem. First time ChildReviews was cleared in another thread:

       Task.Run(() => Application.Current.Dispatcher.Invoke((Action)delegate
                    {
                        GetChildReviews();
                    }); )
    

    and then in another dispather:

    Application.Current.Dispatcher.Invoke((Action)delegate
    {
        GetChildReviews();
    });
    

    I had to remove Task.Run() and now it works