将数据从后台传输到UI线程

时间:2013-06-29 18:33:53

标签: multithreading windows-phone-7 mvvm-light ui-thread

我有一个很长的项目列表(大约100个),我从服务器获取并且我在LongListSelector中向用户显示。每个项目都是图片,名称和描述。

主要问题是,当我将列表发送到ObservableCollection时,它明显减慢了ui的速度。

当我尝试向上和向下滚动时,一切都更糟糕:有时我会在渲染新项目时看到延迟。

我尝试了两种方式,

使用TaskEx.Run():

var answer = await shoppingCartListDataService.GetShoppingListAsync();

var groupedObjects = await TaskEx.Run(() => from item in answer.collection
                                                       group item by
                                                            item.name[0].ToString(CultureInfo.InvariantCulture)
                                                        into it
                                                        orderby it.Key
                                                        select
                                                            new ProductSearchCategoryCollection<ProductItem>(
                                                            it.Key, it.OrderBy(i => i.SumPrice)));
FoundProductItems = new ObservableCollection<ProductSearchCategoryCollection<ProductItem>>(groupedObjects);

Dispatcher.BeginInvoke()(从ThreadWorker调用)

var answer = await shoppingCartListDataService.GetShoppingListAsync();
var groupedObjects = from item in answer.collection
                                     group item by item.aisle
                                     into it
                                     orderby it.Key
                                     select
                                     new ProductSearchCategoryCollection<ProductItem>(it.Key, it.OrderBy(i => i.SumPrice));
Deployment.Current.Dispatcher.BeginInvoke(() =>
                    FoundProductItems = new ObservableCollection<ProductSearchCategoryCollection<ProductItem>>(groupedObjects));

在这两种情况下,ui减速都是值得注意的。

1 个答案:

答案 0 :(得分:0)

Ritch Melton的最终版本:

_items = groupedObjects.ToList();
Deployment.Current.Dispatcher.BeginInvoke(() => 
                        RaisePropertyChanged("FoundProductItems", _items, _items, true)); // using shortcut from MVVMlight