Quelli che il load lo vogliono lazy ma anche un pò weak ...

Tempo fa avevo raccontanto "Come mi piace implementare il Lazy Load con un pizzico di polimorfismo... ", tecnica che avevo visto piacevolmente applicare anche nel noto "Northwind Starter Kit".

A volte mi rendo conto che non solo ci farebbe piacere applicare il lazy load ma ci farebbe anche piacere che quello che carichiamo non occupi permanentemente spazio in memoria. Una interessante alternativa alla referenza permanente di oggetti è sicuramente l'uso delle WeakReference"a weak reference allows the garbage collector to collect an object while still allowing an application to access the object. If you need the object, you can still obtain a strong reference to it and prevent it from being collected".

Un esempio di questa problematica la vedo nelle ipotizzabili proprietà Picture e Photo rispettivamente di Category e di Employee del Northwind. Ecco come ho provato ad applicare l'idea.

   class InternalCategory: Category 
   {
        private bool pictureSpecified = false;
        private WeakReference pictureWeakRef = new WeakReference(null);
        public override byte[] Picture
        {
            get
            {
                if (pictureSpecified)
                {
                    return base.Picture;
                }
                byte[] picture = (byte[])pictureWeakRef.Target;
                if (picture == null)
                {
                    picture = NorthwindProvider.GetCategoryPicture(this.Id);
                    pictureWeakRef.Target = picture;
                }
                return picture;
            }
            set
            {   
                //Se l'immagine viene impostata dall'esterno ne devo mantenere 
                //una referenza forte almeno fino a quando l'entità non viene persistita.
                pictureWeakRef.Target = null;
                pictureSpecified = true;
                base.Picture = value;
            }
        }
    }

Cosa dice MS in merito? Ecco cosa di dice in "Using Weak References".

"Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection."

Ma dice anche....

"Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your application's objects."

Non sembrano due affermazioni contraddittorie? Ci dice che è utile se stiamo trattando oggetti che occupano memoria ma dopo raccomanda di non usarla come soluzione automatica per la gestione della memoria e di preferire sistemi di caching con tanto di policy... su questo ci ragioniamo...

posted @ giovedì 28 dicembre 2006 14:47

Print
Comments have been closed on this topic.
«aprile»
domlunmarmergiovensab
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011