tags:

views:

34

answers:

0

I am trying to make a change in an observable list bound to a wpf control from a background thread. I used for that a class that inherits from IList and INotifyCollectionChanged and all access to the collection are controled with a ReaderWriterLock. However, when I try to add an element to the collection an exception is raised:

NotifyCollectionChangedEventArgs index must be within bounds of the list

with the following code:

    public event NotifyCollectionChangedEventHandler CollectionChanged;
    ...
    public void Add(T item)
    {
        if (Thread.CurrentThread == _dispatcher.Thread)
        {
            DoAdd(item);
        }
        else
        {
            _dispatcher.BeginInvoke((Action) (() => DoAdd(item)));
        }
    }

    private void DoAdd(T item)
    {            

        _sync.AcquireWriterLock(Timeout.Infinite);
        _collection.Add(item);
        if (CollectionChanged != null)
        {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));    
        }
        _sync.ReleaseWriterLock();
    }

However, when I use :

   CollectionChanged(this, new
      NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); 

No exception is raised. Why is exception raised while the element is already added to the collection?