开发者

How to update CollectionViewSource's Source property from Task?

I want to load my CollectionViewSource asynchronously. So I wrote such code:

list1 = new List<int>();
list2 = new List<int>();

Task.Factory.StartNew<Tuple<List<int>, List<int>>>(() =>
{
    // Create and 开发者_如何学运维return tuple with 2 lists
}).ContinueWith(doneTask =>
{
    list1 = doneTask.Result.Item1;
    list2 = doneTask.Result.Item2;
    // update UI
    collectionViewSource1.Source = list1;
    collectionViewSource2.Source = list2;
}, TaskScheduler.FromCurrentSynchronizationContext());

But this code doesn't work.

Exception System.ArgumentException: Must create DependencySource on same Thread as the DependencyObject. occurs.


DependencyObjects have thread affinity, you cannot modify them on a background thread. You should be able to do this using the application's Dispatcher like this:

App.Current.Dispatcher.Invoke((Action)delegate
{
    collectionViewSource1.Source = list1;
    collectionViewSource2.Source = list2;
}, null);

This article on MSDN might provide more relevant information.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜