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

喜欢而已 提交于 2019-12-07 19:55:55

问题


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 ?


回答1:


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?




回答2:


You may use PCache class which is implemented inside PokeIn library. The very good thing is, there is no limitation regarding to this class on FREE edition. It has many functionalities and far better than System.Web.Caching.Cache class..

Additionally, there is a sample project on the link. You may change TimerInterval down to 6 sec with PCache.



来源:https://stackoverflow.com/questions/4823187/system-web-caching-cache-doesnt-seem-to-refresh-itself-on-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!