大家好!我是新手,不想把看不懂的问题留到年后,所以想请朋友们帮我解释一下这段示例代码的意思。
------
尤其是:[3]段中的
public void RemovedCallback(String k, Object v, CacheItemRemovedReason r)
和:[2]段中的
onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
------
[1]---
......
using System.Web.Caching;public partial class Default4 : System.Web.UI.Page
{
    static bool itemRemoved = false;
    static CacheItemRemovedReason reason;
    CacheItemRemovedCallback onRemove = null;
......
}
[2]---
    protected void Button1_Click(object sender, EventArgs e)
    {
        itemRemoved = false;
        onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
        Response.Write("<font color='red'>" +  + "</font>");
        if (Cache["Key1"] == null)
            Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60), TimeSpan.Zero, CacheItemPriority.High, onRemove);
        this.cacheOperate();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        if (Cache["Key1"] != null)
            Cache.Remove("Key1");
        this.cacheOperate();
    }
[3]---
    public void RemovedCallback(String k, Object v, CacheItemRemovedReason r)
    {
        itemRemoved = true;
        reason = r;
    }
    public void cacheOperate()
    {
        if (itemRemoved)
        {
            Response.Write("RemovedCallback event raised.");
            Response.Write("<BR>");
            Response.Write("Reason: <B>Expired</B>");
        }
        else
        {
            Response.Write("Value of cache key: <B>" + Server.HtmlEncode(Cache["Key1"] as string) + "</B>");
        }
    }

解决方案 »

  1.   

    这是Cache问题还是Callback问题啊?能否先解释一下你的代码是要干什么的?
      

  2.   

    这段代码是书中Cache对象的一个示例,用于调用Cache对象的add方法和Remove方法分别向缓存中添加和移除项。
    这里牵扯到一些C#的知识,我对下面的代码没有什么概念,能帮我解释一下吗?
    ---
    [3]段中的
    public void RemovedCallback(String k, Object v, CacheItemRemovedReason r)
    [2]段中的
    onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
    ---
    准确说,我不理解RemovedCallback方法中的3个参数意义,而且示例中的调用...(this.RemovedCallback)代码也没有带参值?
      

  3.   

    那是委托当缓存过期的时候就会触发你查一下MSDN关于 cache中的 add() 还有 insert()  两个方法
    最后的哪个参数就是一个委托
      

  4.   

    http://www.cnblogs.com/Abac/archive/2004/02/11/1166.aspx
    http://msdn2.microsoft.com/zh-cn/library/7kxdx246(VS.80).aspx 可以看看这里...
    第一个连接是介绍cache的
    第二个就是主要说你哪个问题的啦
      

  5.   

    真是感谢,这帖子在这里漂了很久了!哈哈
    能不能留个联络方式,我的Im是:[email protected]
      

  6.   

    (1)中的CacheItemRemovedCallback onRemove = null;是缓存依赖中的一个委托,表示当缓存被remove时产生的回调
    (2)中的onRemove = new CacheItemRemovedCallback(this.RemovedCallback);是new一个委托,里面的参数的一个方法,你可以看看delegate的介绍,
    (3)中的public void RemovedCallback(String k, Object v, CacheItemRemovedReason r)是和委托CacheItemRemovedCallback有相同签名的一个方法具体可以看看委托的用法,结合msdn就差不多了
      

  7.   

    为了说明Cache而搞那么复杂,这本书也太……其实你看看MSDN,知道Cache.Add和Cache.Remove不久行咯。