Cache object with ObjectCache in .Net with expiry time

前端 未结 4 2384
死守一世寂寞
死守一世寂寞 2021-02-20 05:25

I am stuck in a scenario. My code is like below :

Update : its not about how to use data cache, i am already using it and its working , its about expanding it so

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-20 05:48

    Use Double-checked locking pattern:

    var cachedItem = (string)this.GetDataFromCache(cache, cacheKey);
    if (String.IsNullOrEmpty(object)) { // if no cache yet, or is expired
       lock (_lock) { // we lock only in this case
          // you have to make one more check, another thread might have put item in cache already
          cachedItem = (string)this.GetDataFromCache(cache, cacheKey); 
          if (String.IsNullOrEmpty(object)) {
              //get the data. take 100ms
              SetDataIntoCache(cache, cacheKey, cachedItem, DateTime.Now.AddMilliseconds(500));
          }
       }
    }
    

    This way, while there is an item in your cache (so, not expired yet), all requests will be completed without locking. But if there is no cache entry yet, or it expired - only one thread will get data and put it into the cache. Make sure you understand that pattern, because there are some caveats while implementing it in .NET.

    As noted in comments, it is not necessary to use one "global" lock object to protect every single cache access. Suppose you have two methods in your code, and each of those methods caches object using it's own cache key (but still using the same cache). Then you have to use two separate lock objects, because if you will use one "global" lock object, calls to one method will unnecessary wait for calls to the other method, while they never work with the same cache keys.

提交回复
热议问题