c# - 如何处理 MVVM 中并行任务的 ObservableCollection<> 结果?

标签 c# multithreading data-binding mvvm mvvm-light

我在单独的任务中收集数据,我想使用 ObservableCollection<> 将结果数据绑定(bind)到 GUI 组件.所以我的代码是这样的:

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;
    });
  });
}

数据是从执行一些 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; }
}

我更改了 BitmapImagebyte[]数据类型。

最佳答案

你能不能尝试将 Dispatcher.CurrentDispatcher 替换成 Application.Current.Dispatcher 虽然不确定

关于c# - 如何处理 MVVM 中并行任务的 ObservableCollection<> 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3625581/

相关文章:

c# - LINQ to SQL 查询返回重复项

c# - 在 C# 中控制对内部集合的访问 - 需要模式

java - 使用修饰符创建不可变类的好方法(线程安全)

c# - 如何使用 DependencyProperty 设置 TextBox 的绑定(bind)

java - 在 GWT 中将数据绑定(bind)到 UI

c# - Powershell 未在 try/catch 中捕获异常?

c# - 如何使用文本框中的输入作为文件名来命名 .csv 文件?

c - pthread_barrier 不符合我的预期

java - 检查是否持有锁,如果空闲则不锁

javascript - 当子属性更改时重新评估对象绑定(bind)