Let’s take a look at the sample code at first, then I will explain.

   1:  //define a singleton cache
   2:  public class SingletoCache<TKey, TValue> : Cache<TKey, TValue>
   3:  {
   4:      private SingletonCache(){}
   5:      private static SingletoCache<TKey, TValue> mCache;
   6:      private static readonly object mLockObj = new object();
   7:      
   8:      static SingletonCache()
   9:      {
  10:          lock(mLockObj)
  11:          {
  12:              if(mCache == null)
  13:              {
  14:                  mCache = new SingletoCache<TKey, TValue>();
  15:              }
  16:          }
  17:      }
  18:   
  19:      public SingletoCache<TKey, TValue> Instance
  20:      {
  21:          get
  22:          {
  23:              return mCache;
  24:          }
  25:      }
  26:  }
  27:   
  28:   
  29:  public static void Main()
  30:  {
  31:      //some initializing code the the application
  32:   
  33:      //Main is the ideal place to initializing the cache. However, you can do it anywhere
  34:      CacheManager.Instance.Init(()=>{
  35:          
  36:          SingletoCache<int, string>.Instance.BeginAddRange();
  37:   
  38:          CacheManager.Instance.IsIniJobStart = true;
  39:          try
  40:          {
  41:               SingletoCache<int, string>.Instance.AddRange(items);
  42:          }
  43:          finally
  44:          {
  45:               SingletoCache<int, string>.Instance.EndAddRange();
  46:          }
  47:      });
  48:   
  49:     CacheManager.Instance.WaitWhileInitStart();
  50:  }

Init() takes a delegate as parameter. The delegate parameter is invoked asynchronously. It allows you put any code for initializing the cache in the delegate.

BeginAddRange() and EndAddRange() ensure the cache is in write mode which means any read action  on the cache will be suspended while it is in write mode. It is quite useful to initializing a large range of cache data without any concerns that how to do if any read access comes up to the cache.

Last edited Aug 3, 2011 at 3:41 PM by czy, version 2

Comments

No comments yet.