what's the correct way to use locking in AppFabric

314 views Asked by At

I've got a service which updates an AppFabric cache with 8000 objects every four hours. It read a table, creates an object from every record and stores it in the cache.

While the cache is being updated one object at the time consumers can still request objects from the cache. There's not much information available about this, so I want to know if the following code is the correct way to lock and store cache objects in appfabric while other threads can query the cache:

// caching part
private static void CacheDealers(Dictionary<Key<string>, Dealer> dealers)
{
  DataCache cache = Cache.Instance.DealerCache;

  foreach (Key<string> key in dealers.Keys) {
    CacheObject(cache, key.ToString(), dealers[key], mDealerRegionName);
  }
}

    private static void CacheObject(DataCache cache, string key, object obj, string region)
    {
      DataCacheLockHandle lockHandle;

      if (cache.GetAndLock(key, TimeSpan.FromSeconds(10), out lockHandle) == null)
      {
        cache.Put(key, obj, TimeSpan.MaxValue, region);
      }
      else
      {
        cache.PutAndUnlock(key, obj, lockHandle, TimeSpan.MaxValue, region);
      }
    }

    // retrieve part
    public Dealer GetDealer(string lab, string number) {
      Dealer dealer = (Dealer)Cache.Instance.DealerCache.Get(new Key<string>(lab, number).ToString(), mDealerRegionName);
      return dealer;
    }
1

There are 1 answers

0
PhilPursglove On

A locked item can still be read from the cache (though while it's locked it will return the original object, not the updated one), so your GetDealer method should continue to work while the cache is being updated. From MSDN:

Regular Get method calls are not blocked and always access the latest version of the cached object