Rob*_*Day 5 c# asp.net delegates caching
我有下面详述的测试工具。这在页面上有两个标签,它们在 page_load 中设置,由于 updatepanel 和计时器每秒被命中。
Label1 设置为存储在缓存中的日期时间值。Label2 设置为当前日期时间。
缓存设置为从现在起 5 秒的绝对到期时间,缓存上有一个更新回调以重新设置日期时间并使其在另外 5 秒内有效。
我遇到的问题是我每 20 秒看到一次缓存更新,而不是像我期望的那样每 5 秒更新一次。如果我将时间设置为 30 秒,那么它每 40 秒更新一次。
这似乎表明缓存只会每 20 秒过期一次。有谁知道减少这个时间的方法?如果我只是在 5 秒后插入缓存并且没有回调,那么它会按我的预期工作并且每 5 秒删除一次。
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>
Run Code Online (Sandbox Code Playgroud)
后面的代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
您发布的代码的一个问题是您DateTime在回调方法中将 a 放入缓存中,但Nullable<DateTime>在 Page_Load 中检查 a 。
话虽如此,这不是问题。快速浏览一下 Reflector 后,它看起来像是 Cache 实现的一个怪癖:当您使用回调时,它是从每 20 秒运行一次的计时器中调用的。
我推测原因与可重入有关。没有什么可以阻止您从回调方法中访问缓存。当它正在尝试删除某个项目时这样做可能不安全(例如,如果您尝试访问正在删除的缓存项目,则可能存在无限循环)。
因此,当您有回调时,实现会推迟缓存项的删除,直到其计时器运行。
| 归档时间: |
|
| 查看次数: |
1416 次 |
| 最近记录: |