खोज…


कैश में आइटम जोड़ना (सेट)

सेट फ़ंक्शन कैश कैश प्रविष्टि के लिए कुंजी और मूल्य की आपूर्ति करने के लिए CacheItem उदाहरण का उपयोग करके कैश में कैश प्रविष्टि सम्मिलित करता है।

यह फ़ंक्शन ObjectCache.Set(CacheItem, CacheItemPolicy)

private static bool SetToCache()
{
    string key = "Cache_Key";
    string value = "Cache_Value";

    //Get a reference to the default MemoryCache instance.
    var cacheContainer = MemoryCache.Default; 

    var policy = new CacheItemPolicy()
    {
        AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(DEFAULT_CACHE_EXPIRATION_MINUTES)
     };
     var itemToCache = new CacheItem(key, value); //Value is of type object.
     cacheContainer.Set(itemToCache, policy);                
}

System.Runtime.Caching.MemoryCache (ObjectCache)

इस फ़ंक्शन को मौजूदा आइटम फ़ॉर्म कैश मिलता है, और यदि आइटम कैश में मौजूद नहीं है, तो यह valueFetchFactory फ़ंक्शन के आधार पर आइटम प्राप्त करेगा।

    public static TValue GetExistingOrAdd<TValue>(string key, double minutesForExpiration, Func<TValue> valueFetchFactory)
    {            
        try
        {
            //The Lazy class provides Lazy initialization which will evaluate 
            //the valueFetchFactory only if item is not in the cache.
            var newValue = new Lazy<TValue>(valueFetchFactory);

            //Setup the cache policy if item will be saved back to cache.
            CacheItemPolicy policy = new CacheItemPolicy()
            {
                AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutesForExpiration)
            };

            //returns existing item form cache or add the new value if it does not exist.
            var cachedItem = _cacheContainer.AddOrGetExisting(key, newValue, policy) as Lazy<TValue>;

            return (cachedItem ?? newValue).Value;
        }
        catch (Exception excep)
        {
            return default(TValue);
        }
    }


Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow