Search code examples
asp.netcachingsystem.web.caching

System.Web.Caching.Cache doesn't seem to refresh itself on time ?


I am using System.Web.Caching.Cache in an assembly used by my website. I have set some key expiration (absolute expiration) to be 10 seconds (just for debugging). I have also set a callback upon key removal.

The problem is that I see that the cache is getting refreshed after something like 20 seconds and not 10.

I am using HttpRuntime.Cache for this.

Any suggestion for why is that happening ?

I would like to show a code sample, which can shed more light:

public  void OnUpdate(string key
                      , CacheItemUpdateReason reason
                      , out object expensiveObject
                      , out CacheDependency dependency
                      , out DateTime absoluteExpiration
                      , out TimeSpan slidingExpiration)
{
    using (StreamWriter sw = new StreamWriter(@"C:\temp\foo.txt",true))
    {
        sw.WriteLine("Updated Cache at " + DateTime.UtcNow); 
    }
    expensiveObject = 11;
    dependency = null;
    absoluteExpiration = DateTime.UtcNow.AddSeconds(3);
    slidingExpiration = Cache.NoSlidingExpiration;
}
protected void Page_Load(object sender, EventArgs e)
{
    log.WriteInfo("Updated Cache", MethodBase.GetCurrentMethod());
    Page.Cache.Insert("foo", (object)11, null, DateTime.UtcNow.AddSeconds(10), Cache.NoSlidingExpiration, new CacheItemUpdateCallback(OnUpdate));
}

Here, i used Page.Cache. The update should be every 3 seconds. Actually it is performed every 40 seconds, as the below printout shows:

Updated Cache at 1/28/2011 1:38:20 AM Updated Cache at 1/28/2011 1:38:40 AM Updated Cache at 1/28/2011 1:39:00 AM Updated Cache at 1/28/2011 1:39:20 AM Updated Cache at 1/28/2011 1:39:40 AM Updated Cache at 1/28/2011 1:40:00 AM Updated Cache at 1/28/2011 1:40:20 AM Updated Cache at 1/28/2011 1:40:40 AM Updated Cache at 1/28/2011 1:41:00 AM Updated Cache at 1/28/2011 1:41:20 AM Updated Cache at 1/28/2011 1:41:40 AM Updated Cache at 1/28/2011 1:42:00 AM Updated Cache at 1/28/2011 1:42:20 AM Updated Cache at 1/28/2011 1:42:40 AM

What could be the problem ?


Solution

  • The internal cache expire timer only fires every 20 seconds.

    I reflected into System.Web.Caching.CacheExpires

    But then found it already is on SO

    Changing frequency of ASP.NET cache item expiration?