I am looking for a way to do this in C#:
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.
EDIT: [Removed incorrect code block]
You could store a WeakReference to the resource in the dictionary instead of the resource itself. This wouldn't prevent the resource from being garbage collected.
When you fetched a value (the weak reference) from the dictionary, you'd then need to fetch the Target and see whether it's null. If it is, the resource has been garbage collected and you'll need to recreate it. Otherwise, you can return the target as the cached resource.
I don't believe there's much control over how "important" a WeakReference is deemed to be - I don't think you can say that it should make it as far as gen2, for example. Of course you could have some other data structure to make sure that any resource was cached for at least (say) 5 minutes by keeping a strong reference to it for that long.
If you do go for this approach, you may also want to periodically go through the dictionary and clear out entries for which the target has already been garbage collected, to avoid your dictionary getting full of useless entries. If the set of keys is fixed and not too huge, this may not be worth it though, particularly bearing in mind the synchronization you'd probably need.
All this functionality is encapsulated in System.Web.Caching.Cache.
This can be safely used outside ASP.NET and has mechanism for expiration, reloading ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With