.net MemoryCache - notify on item removed

后端 未结 1 430
攒了一身酷
攒了一身酷 2021-02-13 10:30

I\'m using a .net Memory Cache with .NET 4.0 and c#, I want my application to be notified when an item is removed (so I can write that it has been removed to a log file or notif

相关标签:
1条回答
  • 2021-02-13 11:05

    EDIT: If you're using the System.Runtime.Caching.MemoryCache there is a callback on the CacheItemPolicy object for deletion, as well as one for update.

    myMemoryCache.Set("key", null, new CacheItemPolicy() {RemovedCallback = new CacheEntryRemovedCallback(CacheRemovedCallback) /* your other parameters here */});
    
    public void CacheRemovedCallback(CacheEntryRemovedArguments arguments)
    {
        // do what's needed
    }
    

    Initial answer

    When inserting data in the .net cache for the System.Web.Caching namespace you have the option to set a callback to be notified of removal

    Cache.Insert("data", "", null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, new CacheItemRemovedCallback(CacheRemovedCallback));
    
    public string CacheRemovedCallback(String key, object value, System.Web.Caching.CacheItemRemovedReason removedReason)
    {
        // here you can log, renew the value, etc...
    }
    

    There is also a signature for the Insert method that lets you specify a callback to be notified before the item is removed

    0 讨论(0)
提交回复
热议问题