简体   繁体   中英

what's the correct way to use locking in AppFabric

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;
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM