代码之家  ›  专栏  ›  技术社区  ›  Robin Day

Asp.Net-CacheUpdateCallback缓存的绝对过期时间能否小于20秒?

  •  4
  • Robin Day  · 技术社区  · 15 年前

    Label1设置为存储在缓存中的datetime值。Label2设置为当前日期时间。

    从现在起,缓存的绝对过期时间设置为5秒,缓存上有一个更新回调,用于重新设置日期时间并使其在5秒内有效。

    我遇到的问题是,我看到缓存每20秒更新一次,而不是像我预期的那样每5秒更新一次。如果我将时间设置为30秒,那么它每40秒更新一次。

    ASPX公司:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CacheTest.aspx.cs" Inherits="CacheTest" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Cache Test</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:Label ID="Label1" runat="server" Text="" />
                    <br />
                    <asp:Label ID="Label2" runat="server" Text="" />
                    <asp:Timer ID="Timer1" Interval="1000" runat="server" />
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
        </form>
    </body>
    </html>
    

    代码隐藏:

    using System;
    using System.Web;
    using System.Web.Caching;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    public partial class CacheTest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DateTime CachedDateTime = (DateTime)(Cache["DateTime"] ?? DateTime.MinValue);
            if (CachedDateTime == DateTime.MinValue)
            {
                CachedDateTime = System.DateTime.Now;
                Cache.Insert("DateTime", CachedDateTime, null, DateTime.Now.AddSeconds(5), Cache.NoSlidingExpiration, CacheDateTimeUpdateCallback);
            }
            Label1.Text = CachedDateTime.ToString();
            Label2.Text = DateTime.Now.ToString();
        }
    
        private void CacheDateTimeUpdateCallback(string key, CacheItemUpdateReason cacheItemUpdateReason, out object value, out CacheDependency dependencies, out DateTime absoluteExipriation, out TimeSpan slidingExpiration)
        {
            value = System.DateTime.Now;
            dependencies = null;
            absoluteExipriation = DateTime.Now.AddSeconds(5);
            slidingExpiration = Cache.NoSlidingExpiration;
        }
    }
    
    1 回复  |  直到 15 年前
        1
  •  2
  •   to StackOverflow    15 年前

    你发布的代码的一个问题是 DateTime 进入回调方法中的缓存,但检查 Nullable<DateTime>

    尽管如此,这不是问题所在。在使用Reflector快速查看之后,它看起来像是缓存实现的一个怪癖:当您使用回调时,它是从每20秒运行一次的计时器调用的。

    我想原因可能与再进入有关。没有什么可以阻止您从回调方法中访问缓存。在尝试移除某个项的过程中执行此操作可能不安全(例如,如果尝试访问正在移除的缓存项,则可能存在无限循环)。

    因此,当您有一个回调时,实现会推迟缓存项的删除,直到其计时器运行为止。

    推荐文章