如何处理MVVM中并行化任务的ObservableCollection 结果?
我在一个单独的Task中收集数据,我想使用ObservableCollection
将数据绑定到GUI组件。 所以我的代码是这样的:
private ObservableCollection _items; public ObservableCollection Items { get { return _items; } set { if (_items.Equals(value)) { return; } _items = value; RaisePropertyChanged("Items"); } } private void LoadData() { Task task = Task.Factory.StartNew(() => { ObservableCollection itms = _htmlParser.FetchData(...); Dispatcher.CurrentDispatcher.Invoke((Action)delegate { Items = itms; }); }); }
从执行某些HTTP请求的组件中获取数据。 我得到的错误是:
Must create DependencySource on same Thread as the DependencyObject.
我正在使用MVVM Light工具包框架。 我还尝试将结果作为消息发送,但最终出现在同一错误消息中。 任何想法或指针?
编辑:这是问题:
public class MyItem { public string Id { get; set; } public string Name { get; set; } public BitmapImage Image { get; set; } // <--- A big No No because it inherits from the DependencyObject public Uri Uri { get; set; } }
我将BitmapImage
更改为byte[]
数据类型。
您获得的exception(“必须在与DependencyObject相同的线程上创建DependencySource”)表示正在后台线程上创建并在UI线程上使用的内容。 是否有任何UI控件被创建并存储在集合中供UI使用?
我看到ObservableCollection本身是在后台线程上创建的,但我不认为这是问题 – 不幸的是我不在办公室进行编码并确认。
您是否可以尝试将Dispatcher.CurrentDispatcher
替换为Application.Current.Dispatcher
对此不确定