.Net 的 HttpRuntime.Cache 基本運用 .Net 的 HttpRuntime.Cache 基本運用
  .NET       ez      2012-05-04

網頁常常會使用到 cache 機制,來加快網頁速度,以下介紹 HttpRuntime.Cache 的基本運用方式。

using System;

namespace WebApplication
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SetCache("a", "1", 60); //寫入快取 超時時間為60秒
            string temp = GetCache("a"); //讀取快取
            Response.Write(temp);
        }

        /// <summary>
        /// 取的快取
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        protected string GetCache(string key)
        {
            try
            {
                object _cache = System.Web.HttpRuntime.Cache.Get(key);
                if (_cache != null)
                    return (string)_cache;
                else
                    return "";
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 設定快取
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        protected bool SetCache(string key, string value,int timeout)
        {
            try
            {
                System.Web.HttpRuntime.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, timeout), System.Web.Caching.CacheItemPriority.High, null);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

支援平台: Windows 7, Windows Vista SP1 (含) 以後版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (不支援伺服器核心), Windows Server 2008 R2 (SP1 (含) 以後版本支援伺服器核心), Windows Server 2003 SP2


標籤:   .NET

我要留言