2006-08-23

WeakReference

Have you ever wanted to store a time consuming to construct object in a cache, but then it hangs around forever. Try storing a WeakReference to the object instead.

            object cached = new TimeConsumingToConstructObject();
            WeakReference wr = new WeakReference(cached);
            cached = null;
            if(wr.IsAlive) {
                cached = wr.Target;
            } else {
                cached = new TimeConsumingToConstructObject();
            }

No comments: