.NET 4 ObjectCache - Can We Hook Into a “Cache Expired” Event?

前端 未结 3 1968
轮回少年
轮回少年 2021-02-12 23:47

I\'ve got a simple object being cached like this:

_myCache.Add(someKey, someObj, policy);

Where _myCache is declared as Obje

相关标签:
3条回答
  • 2021-02-13 00:36

    There's a property on the CacheItemPolicy called RemovedCallback which is of type: CacheEntryRemovedCallback. Not sure why they didn't go the standard event route, but that should do what you need.

    http://msdn.microsoft.com/en-us/library/system.runtime.caching.cacheitempolicy.removedcallback.aspx

    0 讨论(0)
  • 2021-02-13 00:40

    Late to the party with this one but I've just noticed an interesting difference between CacheItemUpdate and CacheItemRemove callbacks.

    http://msdn.microsoft.com/en-us/library/system.web.caching.cacheitemupdatereason.aspx

    In particular this comment:

    Unlike the CacheItemRemovedReason enumeration, this enumeration does not include the Removed or Underused values. Updateable cache items are not removable and can thus never be automatically removed by ASP.NET even if there is a need to free memory.

    0 讨论(0)
  • 2021-02-13 00:48

    This is my way to use CacheRemovedCallback event when cache expired.

    I share for whom concern.

    public static void SetObjectToCache<T>(string cacheItemName, T obj, long expireTime)
            {
                ObjectCache cache = MemoryCache.Default;
    
                var cachedObject = (T)cache[cacheItemName];
    
                if (cachedObject != null)
                {
                    // remove it
                    cache.Remove(cacheItemName);
                }
    
                CacheItemPolicy policy = new CacheItemPolicy()
                {
                    AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(expireTime),
                    RemovedCallback = new CacheEntryRemovedCallback(CacheRemovedCallback)
                };
    
                cachedObject = obj;
                cache.Set(cacheItemName, cachedObject, policy);
            }
    
    public static void CacheRemovedCallback(CacheEntryRemovedArguments arguments)
                {
                    var configServerIpAddress = Thread.CurrentPrincipal.ConfigurationServerIpAddress();
                    long configId = Thread.CurrentPrincipal.ConfigurationId();
                    int userId = Thread.CurrentPrincipal.UserId();
                    var tagInfoService = new TagInfoService();
                    string returnCode = string.Empty;
    
                    if (arguments.CacheItem.Key.Contains("DatatableTags_"))
                    {
                        // do what's needed
                        Task.Run(() =>
                        {
                        });
                    }
    
                }
    
    0 讨论(0)
提交回复
热议问题