的最佳方法是什么

的最佳方法是什么

本文介绍了从另一个线程更新 ObservableCollection 的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 BackgroundWorker 来更新 ObservableCollection 但它给出了这个错误:

I am using the BackgroundWorker to update an ObservableCollection but it gives this error:

"这种类型的 CollectionView不支持更改其SourceCollection 来自一个线程与 Dispatcher 线程不同."

以最少的工作量解决此问题的最佳和最优雅的方法是什么.我不想写低级基于锁的多线程代码.

What's the best and most elegant way to solve this, with the least amount of work. I don't want to write low level lock-based multi-threading code.

我在网上看到了一些解决方案,但它们已经有好几年了,所以不确定解决这个问题的最新共识是什么.

I have seen some solutions online but they are several years old, so not sure what the latest consensus is for the solution of this problem.

推荐答案

如果 MVVM

public class MainWindowViewModel : ViewModel {

    private ICommand loadcommand;
    public ICommand LoadCommand { get { return loadcommand ?? (loadcommand = new RelayCommand(param => Load())); } }

    private ObservableCollection<ViewModel> items;
    public ObservableCollection<ViewModel> Items {
        get {
            if (items == null) {
                items = new ObservableCollection<ViewModel>();
            }
            return items;
        }
    }

    public void Load() {
        BackgroundWorker bgworker = new BackgroundWorker();
        bgworker.WorkerReportsProgress = true;
        bgworker.DoWork += (s, e) => {
            for(int i=0; i<10; i++) {
                System.Threading.Thread.Sleep(1000);
                bgworker.ReportProgress(i, new List<ViewModel>());
            }
            e.Result = null;
        };
        bgworker.ProgressChanged += (s, e) => {
            List<ViewModel> partialresult = (List<ViewModel>)e.UserState;
            partialresult.ForEach(i => {
                Items.Add(i);
            });
        };
        bgworker.RunWorkerCompleted += (s, e) => {
            //do anything here
        };
        bgworker.RunWorkerAsync();
    }
}

这篇关于从另一个线程更新 ObservableCollection 的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 08:16