tags:

views:

21

answers:

1

I have ASP.Net application with a simple cache helper. Under VS web server it works fine. Under IIS 6.0 cache doesn't work- object, was saved previos, doesn't returns after a minute (with no exception). What could be wrong?

public static class CacheHelper
    {
        public static string Share<T>(T @object, TimeSpan period)
        {
            var uniqueKey = Guid.NewGuid().ToString();
            HttpContext.Current.Cache.Add(uniqueKey, @object, null, Cache.NoAbsoluteExpiration,
                period, CacheItemPriority.BelowNormal, null);
            return uniqueKey;
        }
        public static void ShareViaCookie<T>(string key, T @object, TimeSpan period)
        {
            var cachedObject = GetFromCookie<T>(key);
            if (ReferenceEquals(cachedObject, null))
            {
                var uniqueKey = Share(@object, period);
                HttpContext.Current.Response.Cookies.Set(new HttpCookie(key, uniqueKey)
                {
                    Expires = DateTime.Now.AddYears(1)
                });
            }
            else
            {
                HttpContext.Current.Cache[GetKeyFromCookie(key)] = @object;
            }
        }

        public static T GetShared<T>(string key)
        {
            string uniqueKey = HttpContext.Current.Request.QueryString[key];

            return !string.IsNullOrEmpty(uniqueKey) ? (T)HttpContext.Current.Cache.Get(uniqueKey) : GetFromCookie<T>(key);
        }

        private static T GetFromCookie<T>(string key)
        {
            string uniqueKey = GetKeyFromCookie(key);

            return !string.IsNullOrEmpty(uniqueKey) ? (T)HttpContext.Current.Cache.Get(uniqueKey) : default(T);
        }

        private static string GetKeyFromCookie(string key)
        {
            return HttpContext.Current.Request.Cookies[key]
                .IIf(it => it != null, it => it.Value, it => null);
        }
    }
+1  A: 

Maybe nothing is technically wrong. A cache does not mean that any object will be returned the moment after it is persisted.

If your site is caching a lot of items and the cache is not big enough it may constantly be looking for objects to remove from the cache. In this situations, sometimes the object that has only just been cached can be a good candidate to be removed. If you had room for 100 objects and the cache was full with items that had been accessed at least once, then it may never cache your new object that "has never been accessed". This does actually happen on the odd occasion.

Paul Hadfield