实现缓存移除时通知应用程序

创建一个静态类
该类负责从缓存中检索项并处理回调方法,以将项添加回缓存中。
1.在该类中,创建用于将项添加到缓存中的方法。

2.在该类中,创建用于从缓存中获取项的方法。

3.创建用于处理缓存项移除回调的方法。
该方法必须具备与 CacheItemRemovedCallback 委托相同的函数签名。从缓存中删除项时,会在该方法中执行要运行的逻辑,如重新生成项并将其添加回缓存中。

using System;
using System.Web;
using System.Web.Caching;
public static class ReportManager
{
    private static bool _reportRemovedFromCache = false;
    static ReportManager()
    { }

    public static String GetReport()
    {
        lock (typeof(ReportManager))
        {
            if (HttpContext.Current.Cache["MyReport"] != null)
                return (string)HttpRuntime.Cache["MyReport"];
            else
            {
                CacheReport();
                return (string)HttpRuntime.Cache["MyReport"];
            }
        }
    }

    public static void CacheReport()
    {
        lock (typeof(ReportManager))
        {
            HttpContext.Current.Cache.Add("MyReport",
                CreateReport(), null, DateTime.MaxValue,
                new TimeSpan(0, 1, 0),
                System.Web.Caching.CacheItemPriority.Default,
                ReportRemovedCallback);
        }
    }

    private static string CreateReport()
    {
        System.Text.StringBuilder myReport =
            new System.Text.StringBuilder();
        myReport.Append("Sales Report<br />");
        myReport.Append("2005 Q2 Figures<br />");
        myReport.Append("Sales NE Region - $2 million<br />");
        myReport.Append("Sales NW Region - $4.5 million<br />");
        myReport.Append("Report Generated: " + DateTime.Now.ToString()
            + "<br />");
        myReport.Append("Report Removed From Cache: " +
            _reportRemovedFromCache.ToString());
        return myReport.ToString();
    }

    public static void ReportRemovedCallback(String key, object value,
        CacheItemRemovedReason removedReason)
    {
        _reportRemovedFromCache = true;
        CacheReport();
    }
}

也可以写委托方法:

HttpContext.Current.Cache.Insert (
        "MyReport",
        CreateReport(),
        new CacheDependency ("C:\\CacheDemo\\Dependence"),
        Cache.NoAbsoluteExpiration,
        Cache.NoSlidingExpiration,
        CacheItemPriority.Default,
        new CacheItemRemovedCallback (CreateReport)

);

页面调用:
protected void Page_Load(object sender, EventArgs e)
{
    this.Label1.Text = ReportManager.GetReport();
}

 

原文地址:https://www.cnblogs.com/goooto/p/1129627.html