简体   繁体   中英

Notification on a 3rd party List change

I have a List as a property of an object in a 3rd party library. I want to get notified when this list changes. Is there any way I can achieve this? I do not own the object's code so I cannot convert it to ObservableCollection.

public sealed class ThirdPartyObject
{
    public List<string> Names { get; } = new List<string>();
}

So basically I need a mechanism to be notified in my client code when a change happens in the Names list.

I tried something like this, but it does not work.

var col = new ObservableCollection<string>(myObj.Names);
col.CollectionChanged += (sender, args) =>
{
    // notify
};

If the library does not have any event or callback you cannot get a notification straight away.

You could perhaps modify the library by dissemble it and recompiling. But this will possibly violate the license agreement with the library author if there is any. It might also be possible to do at runtime, but I would recommend against both alternatives since it will make it likely to break if a new version of the library is released.

A workaround would be to use polling. Create a timer of you choice that periodically compares the current list with a saved copy (keep thread safety in mind when doing this), raises an event for any items that are different, and creates a new copy of the list. Using a poller will mean that events are not raised when they happen, and it will use some resources to compare the lists even if no changes has been made. On the other hand, if frequent changes occur, it might be better to raise a few infrequent events rather than for each change.

If you are not care about duplicates or ordering you can use a hashSet to compare two lists:

        var newItems = newList.ToHashSet();
        var removedItems = oldList.ToHashSet();
        var intersection = newItems.ToHashSet();
        intersection.IntersectWith(removedItems);
        removedItems.ExceptWith(intersection);
        newItems.ExceptWith(intersection);

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