ObservableCollection 之批次更新

发表于: 12/12/2022

C Sharp

ObservableCollection

使用示例

using (collection.BatchUpdate())
{
    collection.Add(...);
    ... // Some Addition
    collection.Remove(...);
    ... // Some Removal
}
// And then only one time OnCollectionChanged trigged.

实现代码

public class BulkObservableCollection<T> : ObservableCollection<T>
{
    protected bool _suppressNotification = false;

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (!_suppressNotification)
            base.OnCollectionChanged(e);
    }

    public IDisposable BatchUpdate()
    {
        _suppressNotification = true;
        return new UpdateToken(this);
    }

    private class UpdateToken : IDisposable
    {
        private BulkObservableCollection<T> oc;
        public UpdateToken(BulkObservableCollection<T> cl)
        {
            oc = cl ?? throw new ArgumentNullException(nameof(cl));
        }
        public void Dispose()
        {
            oc._suppressNotification = false;
            oc.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }
    }
}