簡體   English   中英

類中的ASP.NET對象緩存

[英]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中

  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);
}

那是近一年前的事,自那以后已經有所發展,您可以閱讀我關於它的博客文章 ,讓我知道這是否有用。

您的緩存引用需要代碼中的所有項目都可以訪問- 相同的引用。

如果每次都更新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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM