Tuesday, February 13, 2007

WeakReference

I was asked what WeakReferences can be used for in an interview today. I sure have played with it but, honestly, I haven't really used it in any real world project. The only legid use that I can think of is caching, where objects are cached in memory by means of WeakReference. Subsequent access to the same object will become more efficient. Yet once memory becomes the bottleneck, CLR can always reclaim the memory and the objects can always be re-generated later from persistent storage (Database, file, etc). But even this is not ideal: an efficient cache manager would implement some type of replacement algorithm, LRU (least recent used) or LFU (least frequently used), etc. These requirements would make the use of WeakReferences much less effective than it seemed. Another potential use of it is so called "Weak Delegates", to prevent the leakage of event handler --- in case you forget to remove it from the delegate chain. IMO a WeakReference isn't really the best solution here either: when the strong reference to the underlying event handler is lost, it implys that the application is intended NOT to handle the event any more. With WeakReference, the event handler is still being called until garbage collection claims it through the WeakReference, which introduces some sort of random behavior to the application. So is there really a real world necessitiy for WeakReferences?