Async Viewmodel构造函数初始化数据

时间:2017-12-21 17:00:20

标签: c# wpf mvvm async-await

我已按照Async OOP中定义的模式创建了一个视图模型,该模型从两个来源读取数据。但是,当我尝试为集合设置CollectionViewSource和过滤器时,我得到异常Additional information: Must create DependencySource on same Thread as the DependencyObject.,或者在过滤数据时,我得到以下异常The calling thread cannot access this object because a different thread owns it.

属性定义如下

    public NotifyTaskCompletion InitializationNotifier{ get; set; }
    public Task Initialization => InitializationNotifier.Task;

viewmodel构造函数定义InitializationNotifier,如下所示:

    InitializationNotifier = new NotifyTaskCompletion(InitializeAsync());

任务定义如下:

    private async Task InitializeAsync()
    { 
      var aDataSource = await Task.Run(() => ADataSource.Get(1, 2));
      var bDataSource = await Task.Run(() => new BDataSource(1, 2);
      PrepareData(aDataSource, bDataSource); // creates List<T> for different categories
      SetupCollections(); // Creates Observable collections from List<T>
      SetupCVSAndFilters();    // Creates CollectionViewSource for different categories
    }

    private void SetupCollections()
    {
        AStars = new ObservableCollection<IAEntity>(m_aStars);
        BStars = new ObservableCollection<IAEntity>(m_bStars);
    }
    // Setup Collectionview source and Filters
    // Get an exception: 
    // Additional information: Must create DependencySource on same Thread as the DependencyObject.
    private void SetupCVSAndFilters()
    {
        AStarsCVS = new CollectionViewSource { Source = AStars };
        BStarsCVS = new CollectionViewSource { Source = BStars };
        AStarsCVS.View.Filter = FilterCompareData;
        BStarsCVS.View.Filter = FilterCompareData;
    }

view / viewmodel在不使用Async / Task的情况下运行良好,但是来自数据源的提取非常耗时(PInvoke s)我有多个标签可以读取不同的数据我非常感谢指导,以帮助我了解Task / Async

的用法出错

1 个答案:

答案 0 :(得分:1)

每次调用Task.Run()时,都会创建一个新线程。您获得的例外情况与您的线程试图以他们不应该的方式访问彼此有关。我不认为我只能通过你提供的代码看出它出了什么问题,但我可以告诉你,在WPF中,线程可以使用{{3来访问其他线程的对象}}

看起来您可能无法获得您正在寻找的异步编程的好处。一个接一个地有两个await语句,这意味着第一个任务将在第二个任务开始之前完成。我想你想要Dispatcher.BeginInvoke()