注册 登录
编程论坛 ASP.NET技术论坛

一周都没搞明白的Cache,只能请教各位DX了

whoisliang 发布于 2012-03-27 23:43, 648 次点击
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Caching" %>
<script runat="server">
   static CacheItemRemovedCallback oncallback=null;
   static CacheDependency dep =null;
    protected static void callback(string s, object o, CacheItemRemovedReason r)
    {
        if (r == CacheItemRemovedReason.DependencyChanged)
        {
            if (HttpRuntime.Cache[s] == null)
            {
                object b = HttpRuntime.Cache["abc"];
                HttpRuntime.Cache.Insert(s, "DependencyChanged", null, DateTime.Now.AddSeconds(55), Cache.NoSlidingExpiration, CacheItemPriority.Normal, oncallback);
                b = HttpRuntime.Cache["abc"];
                return;
            }
        }
        else
        {
            if (r == CacheItemRemovedReason.Expired)
            {
                HttpRuntime.Cache.Insert(s, "Expired",dep , DateTime.Now.AddSeconds(15), Cache.NoSlidingExpiration, CacheItemPriority.Normal, oncallback);
            }
        }  
    }
    void Application_Start(object sender, EventArgs e)
    {
        // 在应用程序启动时运行的代码
        oncallback += new CacheItemRemovedCallback(callback);
        oncallback1 += new CacheItemRemovedCallback(callback1);
        dep = new CacheDependency(Server.MapPath("~/") + "abc.txt");      
        HttpRuntime.Cache.Insert("abc", "123", dep, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, oncallback);
    }
</script>

说明:
1)根目录下有一abc.txt;
2)另有一default.aspx,后台代码很简单:
    if(Cache["abc"]!=null
        Response.Write(Cache["abc"].ToString());
3)我的程序原本目的是:
    a)启动后让CACHE依赖abc.txt,当我人为改了abc.txt内容之后,就会进入if (r == CacheItemRemovedReason.DependencyChanged)中执行;
    b)这样就会重新安装一个绝对定位时间55秒后过期的Cache;
    c)当再次过期到来时,就会进入if (r == CacheItemRemovedReason.Expired)
中执行,也就是说重新安装一个依赖abc.txt的Cache.

实验发现结果完全和我想像的不一样???????????? object b总是null????

如果:
    protected static void callback(string s, object o, CacheItemRemovedReason r)
    {
        if (r == CacheItemRemovedReason.DependencyChanged)
        {
            if (HttpRuntime.Cache[s] == null)
            {
                object b = HttpRuntime.Cache["abc"];
                HttpRuntime.Cache.Insert(s, "DependencyChanged", dep, DateTime.Now.AddSeconds(55), Cache.NoSlidingExpiration, CacheItemPriority.Normal, oncallback);
                b = HttpRuntime.Cache["abc"];
                return;
              }
        }
    }
则会出现椎栈溢出异常,真是搞不明白????????
请教各位大牛,我在此叩首了!只有20分,全送了.
2 回复
#2
wxm1984272012-03-29 16:27
回复 楼主 whoisliang
大哥,你做这个有什么用?你做这个的想法是怎么样的?
#3
whoisliang2012-03-30 20:47
回复 2楼 wxm198427
学习呀.怎么就没有高手给我解惑呢?
1