Cache object with ObjectCache in .Net with expiry time

前端 未结 4 2382
死守一世寂寞
死守一世寂寞 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 06:10

    You will have to use locking to make sure request is not send when cache is expired and another thread is getting it from remote/slow service, it will look something like this (there are better implementations out there that are easier to use, but they require separate classes):

    private static readonly object _Lock = new object();
    
    ...
    
    object = (string)this.GetDataFromCache(cache, cacheKey);
    
    if(object == null)
    {
       lock(_Lock)
       {
            object = (string)this.GetDataFromCache(cache, cacheKey);
            if(String.IsNullOrEmpty(object))
            {
               get the data // take 100ms
               SetDataIntoCache(cache, cacheKey, object, DateTime.Now.AddMilliseconds(500));
            }
       }
    }
    
    return object;
    

    Also, you want to make sure your service doesn't return null as it will assume that no cache exists and will try to get the data on every request. That is why more advanced implementations typically use something like CacheObject, which supports null values storage.

提交回复
热议问题