我正在分析其他人编写的 silverlight 组件。 我发现了很多热点和瓶颈,现在我遇到了这个:
public static class CollectionExtensions
{
public static void AddRange<T>(this ObservableCollection<T> collection, IEnumerable<T> items)
{
foreach (var item in items)
{
collection.Add(item);
}
}
}
这个扩展方法当然是在ObservableCollection中添加了AddRange方法,但是计算量还是比较大的。 有没有人有更好的实现方式,或者对如何提高这段代码的性能有任何建议?
谢谢
最佳答案
多次调用 Add
会导致多次引发 INotifyCollectionChanged
,这通常会导致 UI 自行重绘。
虽然 Lee 的回答在技术上是正确的,即在添加所有项目后引发 Reset
事件是正确的方法,但我从经验中发现许多网格控件(例如)并不主动支持重置
事件。
最普遍支持的选项是修改集合远离 ObservableCollection
并重新创建 ObservableCollection
属性本身。
换句话说,您的 ObservableCollection
在您的 VM 上定义如下...
private ObservableCollection<MyItem> _items;
public ObservableCollection<MyItem> Items {
get { return _items;}
set
{
_items = value;
OnPropertyChanged(()=> Items);
}
}
...添加您的新项目如下...
var tempColl = _items.ToList();
tempColl.AddRange(newItems);
Items = new ObservableCollection(tempColl);
关于此技术要记住的另一件事是它是线程安全的,因为如果您重新创建 ObservableCollection
,您可以从后台线程向 ObservableCollection
添加项目.普通的 ObservableCollection
不能通过来自非 Dispatcher 线程的 Add
方法添加项目。
关于c# - 优化 C# 代码片段、ObservableCollection 和 AddRange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35597364/