[英]ASP.NET Object Caching in a Class
我正在嘗試創建一個緩存類來緩存頁面中的某些對象。 目的是使用ASP.NET框架的緩存系統,但將其抽象為單獨的類。 似乎緩存不會持續。
有任何想法我在這里做錯了嗎? 是否有可能將對象自身緩存到Page的外部?
編輯:添加了代碼:
插入緩存
Cache c = new Cache();
c.Insert(userid.ToString(), DateTime.Now.AddSeconds(length), null, DateTime.Now.AddSeconds(length), Cache.NoSlidingExpiration,CacheItemPriority.High,null);
從緩存中獲取
DateTime expDeath = (DateTime)c.Get(userid.ToString())
即使我確實擁有了鑰匙,我在c.Get上也得到了null。
該代碼與頁面本身在不同的類中(頁面使用它)
謝謝。
您可以通過多種方式將對象存儲在ASP.NET中
您要存儲什么類型的數據,您如何認為必須保留這些數據?
就在去年年初,我寫了一篇關於我一直在寫的緩存框架的博客文章,這使我可以做以下事情:
// Get the user.
public IUser GetUser(string username)
{
// Check the cache to find the appropriate user, if the user hasn't been loaded
// then call GetUserInternal to load the user and store in the cache for future requests.
return Cache<IUser>.Fetch(username, GetUserInternal);
}
// Get the actual implementation of the user.
private IUser GetUserInternal(string username)
{
return new User(username);
}
那是近一年前的事,自那以后已經有所發展,您可以閱讀我關於它的博客文章 ,讓我知道這是否有用。
您的緩存引用需要代碼中的所有項目都可以訪問- 相同的引用。
如果每次都更新Cache
類,那么您做錯了。
我做了幾乎相同的事情,但是使用了不同的代碼(它對我有用):( CacheKeys是一個枚舉)
using System;
using System.Configuration;
using System.Web;
using System.IO;
public static void SetCacheValue<T>(CacheKeys key, T value)
{
RemoveCacheItem(key);
HttpRuntime.Cache.Insert(key.ToString(), value, null,
DateTime.UtcNow.AddYears(1),
System.Web.Caching.Cache.NoSlidingExpiration);
}
public static void SetCacheValue<T>(CacheKeys key, T value, DateTime expiration)
{
HttpRuntime.Cache.Insert(key.ToString(), value, null,
expiration,
System.Web.Caching.Cache.NoSlidingExpiration);
}
public static void SetCacheValue<T>(CacheKeys key, T value, TimeSpan slidingExpiration)
{
HttpRuntime.Cache.Insert(key.ToString(), value, null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
slidingExpiration);
}
public static T GetCacheValue<T>(CacheKeys key)
{
try
{
T value = (T)HttpRuntime.Cache.Get(key.ToString());
if (value == null)
return default(T);
else
return value;
}
catch (NullReferenceException)
{
return default(T);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.