djskinner
djskinner

Reputation: 8125

Running expensive operations on ObservableCollection.CollectionChanged

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?

Upvotes: 3

Views: 568

Answers (2)

Hans Passant
Hans Passant

Reputation: 941605

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

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564433

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.

Upvotes: -2

Related Questions