简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM