Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting modifications with an IEnumerable

I have a question that I am surprised hasn't already been asked in exactly this format.

If I have an IEnumerable that is generated based on iterating through a source of data, (and using a yield return statement), how can I detect when there has been a modification to the source after an access via an Enumerator that was generated via a GetEnumerator call?

Here is the strange part: I'm not multi-threading. I think my question has a flaw in it somewhere, because this should be simple. . . I just want to know when the source has changed and the iterator is out of date.

Thank you so much.

like image 641
BlackVegetable Avatar asked Feb 13 '26 09:02

BlackVegetable


2 Answers

You would need to handle creating the enumerator yourself in order to track this information, or, at a minimum use yield return; with your own type of modification tracking in place.

Most of the framework collection classes, for example, keep a "version" number. When they make an enumerator, they keep a snapshot of that version number, and check it during MoveNext(). You could make the same check before calling yield return XXX;

like image 57
Reed Copsey Avatar answered Feb 14 '26 23:02

Reed Copsey


Most collection classes in the .NET BCL uses a version attribute for change tracking. That is: the enumerator is constructed with a version number (integer) and checks the original source of the version number is still the same each iteration (when movenext is called). The collection in turn increments the version attribute each time a modification is made. This tracking mechanism is simple and effective.

2 other ways i've seen are:

Having the collection hold an internal collection containing weak references to outstanding enumerators. and each time a modification is made to the collection, it makes each enumerator which is still alive invalid.

Or implementing events in the collection ( INotifyCollectionChanged ) and simply register on that event in the enumerator. And if raised, mark the enumerator as invalid. This method is relatively easy to implement, generic and comes without to much overhead but requires your collection to support events

like image 39
Polity Avatar answered Feb 14 '26 21:02

Polity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!