如何在线程中复制 Observable 集合中的列表

How to Copy List in Observable Collection in Thread

我有一个后台工作人员 fills/refills 一个列表,在重新填充和编辑列表后,我将这个列表复制到一个可观察列表中:

this.OBSMailCountList = new ObservableCollection<IMailCount>(_allMailCounts);

问题是集合绑定到实时图表,在列表中复制后我得到

错误:

"The Value can not be NULL".

我的问题是:

如何在线程中复制带有绑定的 Observable 集合?

Dispatcher.Invoke( Action ) 将用于调用 UI 线程。

Dispatcher.Invoke(() =>
{
      // Set property or change UI compomponents.           
      OBSMailCountList = new ObservableCollection<IMailCount>(_allMailCounts);   
}); 

你的问题是你在调用可观察集合构造函数时有 _allMailCounts == null。您可以像这样检查 null

if(_allMailCounts != null)
    OBSMailCountList = new ObservableCollection<IMailCount>(_allMailCounts);

以下是问题"how to work with ObservableCollection from another tread"的答案:


绑定到通常定义的可观察集合

ObservableCollection<IMailCount> _collection = new ObservableCollection<IMailCount>();
public ObservableCollection<IMailCount> Collection
{
    get { return _collection; }
    set
    {
        _collection = value;
        OnPropertyChanged();
    }
}

在另一个线程中以这种方式工作:

// create a copy as list in UI thread
List<IMailCount> collection = null;
Dispatcher.Invoke(() => collection = new List<IMailCount>(_collection));

// when finished working set property in UI thread
Dispatcher.InvokeAsync(() => Collection = new ObservableCollection<IMailCount>(collection));