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

About bpostaci
Escalation Engineer in Microsoft.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: