类中的ASP.NET对象缓存

Rom*_*man 0 asp.net caching

我正在尝试创建一个缓存类来缓存页面中的一些对象.目的是使用ASP.NET框架的缓存系统,但将其抽象为单独的类.似乎缓存不会持续存在.

我在这里做错了什么想法?是否有可能将对象缓存到页面本身?

编辑:添加代码:

插入缓存

Cache c = new Cache();
c.Insert(userid.ToString(), DateTime.Now.AddSeconds(length), null, DateTime.Now.AddSeconds(length), Cache.NoSlidingExpiration,CacheItemPriority.High,null);
Run Code Online (Sandbox Code Playgroud)

从缓存中获取

DateTime expDeath = (DateTime)c.Get(userid.ToString())
Run Code Online (Sandbox Code Playgroud)

即使我确实拥有密钥,我也会在c.Get上获得null.

代码与页面本身不同(页面使用它)

谢谢.

Mat*_*ott 7

有许多方法可以在ASP.NET中存储对象

  1. 页面级项目 - >页面上的属性/字段,可以在请求中的页面生命周期的生命周期中存在.
  2. ViewState - >以序列化的Base64格式存储项目,该格式通过使用PostBack的请求保留.控件(包括页面本身 - 它是一个控件)可以通过从ViewState加载它来保留它们之前的状态.这使得ASP.NET页面的概念成为有状态的.
  3. HttpContext.Items - >请求生命周期中要存储的项的字典.
  4. 会话 - >通过会话提供多个请求的缓存.会话缓存机制实际上支持多种不同的模式.
    • InProc - 项目由当前进程存储,这意味着如果进程终止/回收,会话数据将丢失.
    • SqlServer - 项目被序列化并存储在SQL Server数据库中.项目必须是可序列化的.
    • StateServer - 项目被序列化并存储在StateServer进程的单独进程中.与SqlServer一样,项必须是可序列化的.
  5. 运行时 - 存储在运行时缓存中的项目将保留当前应用程序的生命周期.如果应用程序被回收/停止,则项目将丢失.

您试图存储什么类型的数据,以及您认为它必须如何保留?

就在去年年初,我写了一篇关于我一直在编写的缓存框架的博客文章,它允许我做类似的事情:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

那是近一年前的事了,从那以后它已经有所改进了,你可以阅读我的博客文章,让我知道是否有用.