如何处理ObservableCollection<>由MVVM中的并行任务导致的? [英] How to handle ObservableCollection<> result from a parallelized Task in MVVM?
问题描述
ObservableCollection<>
将数据绑定到GUI组件。所以我的代码是这样的: private ObservableCollection< MyItem> _items;
public ObservableCollection< MyItem>项目
{
get {return _items; }
set
{
if(_items.Equals(value))
{
return;
}
_items = value;
RaisePropertyChanged(Items);
}
}
private void LoadData()
{
任务任务= Task.Factory.StartNew(()=>
{
ObservableCollection< MyItem> itms = _htmlParser.FetchData(...);
Dispatcher.CurrentDispatcher.Invoke((Action)委托
{
Items = itms ;
});
});
}
从执行某些HTTP请求的组件中获取数据。我得到的错误是:
必须在DependencyObject的同一线程上创建DependencySource。
我正在使用MVVM Light工具箱框架。我也试图发送结果作为一个消息,但最终在同一个错误消息。任何想法或指针?
编辑:这是问题:
public class MyItem
{
public string Id {get;组; }
public string Name {get;组; }
public BitmapImage Image {get;组; } //< ---一个大的否否,因为它继承自DependencyObject
public Uri Uri {get;组;
}
我更改了 BitmapImage
到 byte []
数据类型。
异常你得到(必须在DependencyObject的同一个线程上创建DependencySource)表示在后台线程上创建的东西并在UI线程上使用。是否有任何UI控件被创建并存储在集合中以供UI使用?
我看到ObservableCollection本身是在后台线程上创建的,但是我不要以为是这个问题 - 不幸的是我不在办公室进行编码并确认。
I am gathering data in a separate Task and I want to data bind the result to a GUI component using an ObservableCollection<>
. So my code goes something like this:
private ObservableCollection<MyItem> _items;
public ObservableCollection<MyItem> Items
{
get { return _items; }
set
{
if (_items.Equals(value))
{
return;
}
_items = value;
RaisePropertyChanged("Items");
}
}
private void LoadData()
{
Task task = Task.Factory.StartNew(() =>
{
ObservableCollection<MyItem> itms = _htmlParser.FetchData(...);
Dispatcher.CurrentDispatcher.Invoke((Action)delegate
{
Items = itms;
});
});
}
The data is fetched from a component doing some HTTP requests. The error I am getting is:
Must create DependencySource on same Thread as the DependencyObject.
I am using the MVVM Light toolkit framework. I also tried to send the result as a message, but that ended up in the same error message. Any ideas or pointers?
EDIT: Here's the issue:
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; }
}
I changed the BitmapImage
to a byte[]
data type.
The exception you're getting ("Must create DependencySource on same Thread as the DependencyObject") indicates that something's being created on a background thread and used on the UI thread. Are there any UI controls being created and stored in the collection for use by the UI?
I see that the ObservableCollection itself is being created on a background thread, but I don't think that's the issue -- unfortunately I'm not in the office to code and confirm that.
这篇关于如何处理ObservableCollection<>由MVVM中的并行任务导致的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!