Could someone please be kind enough to explain to me what the purpose of the BlockReentrancy Method is in the ObservableCollection<T> ?
MSDN shows the following as an example:
//The typical usage is to wrap an OnCollectionChanged call within a using scope, as in the following example:
using (BlockReentrancy())
{
// OnCollectionChanged call
}
But this doesn’t seem to clarify for me what the purpose is. Anyone care to explain?
An
ObservableCollectionimplementsINotifyCollectionChangedand so it has aCollectionChangedevent. If there is a subscriber to this event, they could further modify the collection while the collection is already in the process of notification. Since theCollectionChangedevent keeps track of exactly what changed, this interaction can get very messy.As a result, the
ObservableCollectionallows, as a special case, a single subscriber of theCollectionChangedevent to modify the collection from its handler. But it disallows modifying the collection from theCollectionChangedhandler if there are two or more subscribers to theCollectionChangedevent.The pair of methods
BlockReentrancyandCheckReentancyare used to implement this logic. TheBlockReentrancyis used at the start of theOnCollectionChangedmethod andCheckReentancyis used in all methods that modify the collection.