天天看點

緩存通用管理類 + 緩存 HttpContext.Current.Cache 和 HttpRuntime.Cache 的差別

 以前寫asp.net時用HttpContext.Current.Cache存緩存很好用,今天寫了一個windows服務程式,HttpContext.Current.Cache存緩存的時候還好,取的時候一直報錯“未将對象引用到執行個體”很郁悶,查詢了一下資料才明白引用程式緩存要用HttpRuntime.Cache...

  我們先看MSDN上的解釋:

        HttpContext.Current.Cache:為目前 HTTP 請求擷取Cache對象。

        HttpRuntime.Cache:擷取目前應用程式的Cache。

附帶的寫了一個操作緩存的通用類,在應用程式中使用,如果要在asp.net中有,隻需把HttpRuntime.Cache改為HttpContext.Current.Cache即可,代碼如下:

複制代碼

using System;

/// <summary>

/// author:Stone_W

/// date:2010.12.1

/// desc:緩存的管理類

/// 注意:要添加對引用 System.Web

/// </summary>

public class MyCacheTools : System.Web.SessionState.IRequiresSessionState

{

    #region 存入Cache

    /// <summary>

    /// 存入Cache

    /// </summary>

    /// <param name="key">緩存key</param>

    /// <param name="value">緩存的值</param>

    /// <param name="time_HH">存xx小時</param>

    /// <returns>是否執行成功[bool]</returns>

    public static bool SetCache(string key, object value, int time_HH)

    {

        bool result = false;

        try

        {

            DateTime dt = DateTime.Now.AddHours(time_HH);

            System.Web.HttpRuntime.Cache.Insert(key, value, null,

                dt, System.Web.Caching.Cache.NoSlidingExpiration);

            result = true;

        }

        catch (Exception ex) { }

        return result;

    }

    #endregion

    #region 取得Cache

    /// 取得Cache

    /// <param name="key">key</param>

    /// <returns>object類型</returns>

    public static object GetCache(string key)

        return System.Web.HttpRuntime.Cache.Get(key);

    #region 查詢Cache是否存在

    /// 查詢Cache是否存在

    /// <param name="key">key 值</param>

    /// <returns>bool</returns>

    public static bool IsCacheExist(string key)

        object temp = System.Web.HttpRuntime.Cache.Get(key);

        if (null != temp)

}

本文轉自王磊的部落格部落格園部落格,原文連結:http://www.cnblogs.com/vipstone/archive/2010/12/01/1893619.html,如需轉載請自行聯系原作者

繼續閱讀