什么是更新从另一个线程一个ObservableCollection的最佳方式? [英] What's the best way to update an ObservableCollection from another thread?

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

问题描述

我现在用的是的BackgroundWorker 来更新的ObservableCollection ,但它给这个错误:

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

这种类型的的CollectionView 的确实
不支持更改其
SourceCollection 从线程
与发送器线程不同的。

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

什么是最好的和最优雅的方式来解决这个问题,与工作最少。我不想写低水平基于锁的多线程代码。

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的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆