Cache object with ObjectCache in .Net with expiry time

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

    By the way, 500 milliseconds is too small time to cache, you will end up lots of CPU cycle just to add/remove cache which will eventually remove cache too soon before any other request can get benefit of cache. You should profile your code to see if it actually benefits.

    Remember, cache has lot of code in terms of locking, hashing and many other moving around data, which costs good amount of CPU cycles and remember, all though CPU cycles are small, but in multi threaded, multi connection server, CPU has lot of other things to do.

    Original Answer https://stackoverflow.com/a/16446943/85597

    private string GetDataFromCache(
                ObjectCache cache, 
                string key, 
                Func valueFactory)
    {
        var newValue = new Lazy(valueFactory);            
    
        //The line below returns existing item or adds 
        // the new value if it doesn't exist
        var value = cache.AddOrGetExisting(key, newValue, DateTimeOffset.Now.AddMilliseconds(500)) as Lazy;
        // Lazy handles the locking itself
        return (value ?? newValue).Value;
    }
    
    
    // usage...
    
    
    object = this.GetDataFromCache(cache, cacheKey, () => {
    
          // get the data...
    
          // this method will be called only once..
    
          // Lazy will automatically do necessary locking
          return data;
    });
    

提交回复
热议问题