La Cache e oggetti singleton

In alcuni nostri progetti potrebbe apparire del codice come quello che segue.

class C
{
   public static C Current
   {
      C c_currentInstance = (C) HttpContext.Current.Cache["c_currentInstance"];
      if(c_currentInstance == null)
      {
         c_currentInstance = new C();
         HttpContext.Current.Cache.Add("c_currentInstance", c_currentInstance, [cut]);
      }
      return c_currentInstance;
   }

}

Ogni chiamata a C.Current implica una ricerca per chiave ed un cast. Ma tutta questa burocraziona algoritmica è evitabile? Si potrebbe fare così:

class C
{
   static c_currentInstance;
   
   public static C Current
   {
      if(c_currentInstance == null)
      {
         c_currentInstance = new C();
         HttpContext.Current.Cache.Add("c_currentInstance", c_currentInstance, [cut], 
           new CacheItemRemovedCallback(OnCacheItemRemovedCallback));
      }
      return c_currentInstance;
   }

   static void OnCacheItemRemovedCallback([cut])
   {
       c_currentInstance = null;
   }

}

...certo le soluzioni illustrate non stanno considerando gli eventuali problemi di chiamate concorrenti, non era infatti questo il problema trattato nel corrente post. Nel caso di necessità comunque ricordate che potete "Implementare Singleton con Volatile" come proposto da Alessandro.

posted @ venerdì 25 novembre 2005 11:44

Print

Comments on this entry:

# re: La Cache e gli oggetti singleton

Left by M.rkino at 25/11/2005 14:40
Gravatar
La scelta della Cache non è infatti adottata in tutti i progetti ma "in alcuni nostri progetti". Solitamente la scelta di usare la cache è legata a progetti web con eventuali dipendenze e/o expiration e/o sliding time.
Comments have been closed on this topic.
«aprile»
domlunmarmergiovensab
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011