views:

145

answers:

2

In my model I need to be made aware when a particular collection is changed so I am subscribing to the CollectionChanged event of the ObservableCollection. This is working really well except that the operation is fairly resource expensive.

So when client code does:

foreach(Item i in longList)
{
    model.ObservableCollection.Add(i);
}

I am running the expensive operation for each iteration when all that is important is the result after the final item is added.

Is there a way of cancelling the currently running event handler if another CollectionChanged event is raised whilst the first is still executing - and then proceed to handle the most recent event?

A: 

Not directly. The process you're running will run synchronously - so the next event won't occur until your current process completes.

One alternative in situations like this is to fire a timer on CollectionChanged, and then process on the timer's tick. This way, if you fire CollectionChanged multiple times, the timer will already be enabled, and you'll only get a single "tick" event.

Reed Copsey
Can you elaborate on this further? Wouldn't this only process the first event instead of the most recently raised?
Daniel Skinner
Typically, you "queue" them, but process them when the timer fires. This way, you end up processing all of the events in one method call, avoiding the stream of methods. This is useful in many situations when you have "too many" events firing...
Reed Copsey
+3  A: 

ObservableCollection is not a sealed class. Derive your own and add a BeginUpdate and EndUpdate() method and IsUpdating property.

Hans Passant