To get started, what you're talking about is the basic idea of ββthe IDisposable interface: a deterministic way of allocating resources. Although its main use is to interact with unmanaged resources that require explicit release (or interact with objects that do this), its use is not limited to this.
Unfortunately, this does not meet your last requirement: since it is deterministic, it must be called by someone. That someone was supposed to be Asker.
The only solution I can come up with is to use the WeakReference class in your Giver object. This allows you to maintain a link to an instance that does not prevent it from collecting garbage (after collecting it, your link becomes null ).
Unfortunately, this is not deterministic. Your link will become null (and IsAlive will be false ) after the actual collection of the object, which is not guaranteed at any particular time (or even during the entire life of your application).
Given these caveats, you can do something like this:
public class Giver { private Dictionary<string, WeakReference> cache = new Dictionary<string, WeakReference>(); public object GetResource(string resourceName) { WeakReference output; object returnValue = null; if(cache.TryGetValue(resourceName, out output)) { if(output.IsAlive) returnValue = output.Target; if(returnValue == null) cache.Remove(resourceName); } if(returnValue == null) { returnValue = ...;
source share