I am looking for a way to do this in C#:
- an Asker object will ask a Giver object for Resource objects.
- when asked, Giver will search it's Dictionary for existing matching Resource. If found, it will return the reference of the Resource; otherwise, it will create a the new Resource from database data, save that reference in Dictionary, and finally return the reference.
- the Asker may ask for the same Resource more than once, in which case Giver will return the same Resource from the Dictionary the same number of times.
the Asker may at any time have no use for a given Resource, in which case, it does nothing further to the Resource.
Problem: How can Giver detect for any Resource that it is no longer in use and remove it from the Dictionary? Preferably, Giver should do this without Asker's help.
Is this possible? I can't seem to solve this.
EDIT: Thanks everyone for the great replies. Especially the WeakReferences. I didn't know they were there. But I have 2 main objectives which I could have specified clearer.
- Giver should not rely on Asker to get notified.
- While a given Resource is in use, all of the references must be pointing to the same Resource so that modification to the Resource is reflected in all places where the same Resource is used.
EDIT: [Removed incorrect code block]
WeakReferencein the cache and returns only a single instance of the resource to the asker. As with all solutions, it's not guaranteed to clean up anything (since your object may not, in fact, ever get garbage collected), but if it does, it will.