when CacheItemRemovedCallback is raised HttpContext.Current is null

CacheItemRemovedCallback shows users the value assigned to an item in the cache and then notifies them when the item is removed from the cache. It creates a RemovedCallback method, which uses the signature of the CacheItemRemovedCallback delegate, to notify users when the cache item is removed and uses theCacheItemRemovedReason enumeration to tell them why it was removed.But when you try to use cache with HttpContext.Current it encounter an object not set reference error.

Here is the solution.

Use :HttpRuntime.Cache instead of HttpContext.Current.Cache object

Example::

 public static void DropUser(string key, object value, CacheItemRemovedReason reason)
        {
            List<string> OnlineUserAccounts = null;
            if (HttpRuntime.Cache[CACHE_KEY] != null)
            {
                OnlineUserAccounts = (List<string>)HttpRuntime.Cache[CACHE_KEY];
                if (OnlineUserAccounts.Contains(key))
                {
                    OnlineUserAccounts.Remove(key);
 
                    HttpRuntime.Cache[CACHE_KEY] = OnlineUserAccounts;
                }
            }
        }
 
Happy Codding.
Advertisement