优化C#代码片段,ObservableCollection和AddRange

时间:2016-02-24 08:52:00

标签: c# silverlight optimization collections profiling

我正在分析其他人写的一个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);
        }
    }
}

这个扩展方法,当然,将AddRange方法添加到ObservableCollection中,但它在计算中非常密集。 有没有人有更好的实施,或任何关于如何提高这一部分性能的建议?

谢谢

5 个答案:

答案 0 :(得分:4)

多次调用Add会导致INotifyCollectionChanged多次被提升,导致用户界面自行重绘。

虽然Lee的答案在技术上是正确的,但是一旦添加了所有项目,提出Reset事件是正确的方法,我从经验中发现许多网格控件(例如)没有积极支持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方法向其添加项目。

答案 1 :(得分:1)

此处的成本通常是由于为每个单独添加而引发的更改通知。最好的做法是创建一个针对接受数据范围进行优化的新集合实现。您可以添加所有值,然后引发单个事件,而不是为每个更改提出更改通知,然后将Binding引擎作为单个更新进行处理。此事件可以使大锤Reset,或者您可以提供已更改的项目以及更改的索引。

这是一个在Reset方法上使用单个AddRange通知的示例:

/// <summary>
/// An implementation of <seealso cref="ObservableCollection{T}"/> that provides the ability to suppress
/// change notifications. In sub-classes that allows performing batch work and raising notifications 
/// on completion of work. Standard usage takes advantage of this feature by providing AddRange method.
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
public class ObservableList<T> : ObservableCollection<T>
{
    #region Fields
    private readonly Queue<PropertyChangedEventArgs> _notifications = new Queue<PropertyChangedEventArgs>();
    private readonly Queue<NotifyCollectionChangedEventArgs> _collectionNotifications = new Queue<NotifyCollectionChangedEventArgs>();
    private int _notificationSupressionDepth;
    #endregion

    public ObservableList()
    {
    }
    public ObservableList(IEnumerable<T> collection)
        : base(collection)
    {
    }

    public void AddRange(IEnumerable<T> list)
    {
        using (SupressNotifications())
        {
            foreach (var item in list)
            {
                Add(item);
            }
        }
        OnPropertyChanged("Count");
        OnPropertyChanged("Item[]");
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }

    public void RemoveRange(IEnumerable<T> list)
    {
        using (SupressNotifications())
        {
            foreach (var item in list)
            {
                Remove(item);
            }
        }
        OnPropertyChanged("Count");
        OnPropertyChanged("Item[]");
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }

    public void ReplaceRange(IEnumerable<T> list)
    {
        using (SupressNotifications())
        {
            Clear();
            foreach (var item in list)
            {
                Add(item);
            }
        }
        OnPropertyChanged("Count");
        OnPropertyChanged("Item[]");
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }


    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (_notificationSupressionDepth == 0)
        {
            base.OnCollectionChanged(e);
        }
        else
        {
            //We cant filter duplicate Collection change events as this will break how UI controls work. -LC
            _collectionNotifications.Enqueue(e);
        }
    }

    protected override void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (_notificationSupressionDepth == 0)
        {
            base.OnPropertyChanged(e);
        }
        else
        {
            if (!_notifications.Contains(e, NotifyEventComparer.Instance))
            {
                _notifications.Enqueue(e);
            }
        }
    }

    protected void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    protected IDisposable QueueNotifications()
    {
        _notificationSupressionDepth++;
        return Disposable.Create(() =>
                                     {
                                         _notificationSupressionDepth--;
                                         TryNotify();
                                     });
    }

    protected IDisposable SupressNotifications()
    {
        _notificationSupressionDepth++;
        return Disposable.Create(() =>
        {
            _notificationSupressionDepth--;
        });
    }

    private void TryNotify()
    {
        if (_notificationSupressionDepth == 0)
        {
            while (_collectionNotifications.Count > 0)
            {
                var collectionNotification = _collectionNotifications.Dequeue();
                base.OnCollectionChanged(collectionNotification);
            }

            while (_notifications.Count > 0)
            {
                var notification = _notifications.Dequeue();
                base.OnPropertyChanged(notification);
            }
        }
    }
}

编辑:添加缺少的NotifyEventComparer类和示例Disposable.Create方法

public sealed class NotifyEventComparer : IEqualityComparer<PropertyChangedEventArgs>
{
    public static readonly NotifyEventComparer Instance = new NotifyEventComparer();

    bool IEqualityComparer<PropertyChangedEventArgs>.Equals(PropertyChangedEventArgs x, PropertyChangedEventArgs y)
    {
        return x.PropertyName == y.PropertyName;
    }

    int IEqualityComparer<PropertyChangedEventArgs>.GetHashCode(PropertyChangedEventArgs obj)
    {
        return obj.PropertyName.GetHashCode();
    }
}

//Either use Rx to access Disposable.Create or this simple implementation will do
public static class Disposable
{
    public static IDisposable Create(Action dispose)
    {
        if (dispose == null)
            throw new ArgumentNullException("dispose");

        return new AnonymousDisposable(dispose);
    }

    private sealed class AnonymousDisposable : IDisposable
    {
        private Action _dispose;

        public AnonymousDisposable(Action dispose)
        {
            _dispose = dispose;
        }

        public void Dispose()
        {
            var dispose = Interlocked.Exchange(ref _dispose, null);
            if (dispose != null)
            {
                dispose();
            }
        }
    }
}

答案 2 :(得分:1)

这是由于ObservableCollection在每次将项添加到集合时触发PropertyChanged事件。防止在批量添加项目时触发此事件是您要查看的内容。这是一个优雅的解决方案,虽然我自己没有尝试过。

https://peteohanlon.wordpress.com/2008/10/22/bulk-loading-in-observablecollection/

答案 3 :(得分:0)

您可以在此处查看AddRange方法实现(对于List): http://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs

答案 4 :(得分:0)

该线程中已经有一个可接受的答案,但是对于所有寻求 ObservableRangeCollection 的好实现以支持 AddRange ReplaceRange 的人对于单个CollectionChanged通知,我真的会推荐this piece of code written by James Montemagno