﻿# 分享一個常用的 System.Web.HttpRuntime.Cache 程式碼

在 Web 的世界裡活用 Cache 已經是不可或缺的觀念與技能之一，即便不是 Web 環境，Cache 也是非常重要的技能之一，所以我們現在的專案之中也有越來越多案子需要實做 Cache 機制，以下分享我們常用的 Cache 相關程式碼。

**web.config**

```
<appSettings>
  <add key="EnableCache" value="true"/>
  <add key="CacheDurationSeconds" value="300"/>
</appSettings>
```

**App\_Code\\SiteHelper.cs**

```
using System;
using System.Web.Configuration;

public class SiteHelper
{
    static public object GetCache(string CacheId)
    {
        object objCache = System.Web.HttpRuntime.Cache.Get(CacheId);

        // 判斷 Cache 是否啟用
        if (WebConfigurationManager.AppSettings["EnableCache"] == null
            || !Convert.ToBoolean(WebConfigurationManager.AppSettings["EnableCache"]))
        {
            objCache = null;
            System.Web.HttpRuntime.Cache.Remove(CacheId);
        }

        return objCache;
    }

    /// <summary>
    /// 寫入 Cache 資料 ( 預設 60 秒 )
    /// </summary>
    /// <param name="CacheId"></param>
    /// <param name="objCache"></param>
    static public void SetCache(string CacheId, object objCache)
    {
        if (WebConfigurationManager.AppSettings["CacheDurationSeconds"] != null)
        {
            SetCache(CacheId, objCache, 
                Convert.ToInt32(WebConfigurationManager.AppSettings["CacheDurationSeconds"]));
        }
        else
        {
            SetCache(CacheId, objCache, 60);
        }
    }

    static public void SetCache(string CacheId, object objCache, int cacheDurationSeconds)
    {
        if (objCache != null)
        {
            System.Web.HttpRuntime.Cache.Insert(
                CacheId,
                objCache,
                null,
                System.Web.Caching.Cache.NoAbsoluteExpiration,
                new TimeSpan(0, 0, cacheDurationSeconds),
                System.Web.Caching.CacheItemPriority.High,
                null);
        }
    }
}
```

**使用方式**

```
string strCache1 = SiteHelper.GetCache("Cache1") as string;

if (strCache1 == null)
{
    Response.Write("<p>Cache is empty</p>");

    strCache1 = "OK";
    SiteHelper.SetCache("Cache1", strCache1, 30);
}

Response.Write(strCache1);
```

事實上，在非 Web 的環境下，例如 Windows Form 或 WPF 等，也可以有效利用 **System.Web** 組件提供的種種功能，也包括 Cache 機制，只要在專案內加入 **System.Web** 的參考就可以使用了，雖然習慣寫 Windows Form 的人可能會覺得怪怪的，但實際上 **System.Web** 明明就是 .NET Framework 內建的組件，沒什麼不能用的道理！

前天看了一個訪談 Scott Hanselman 的影片：[ARCast.TV - Scott Hanselman on scaling websites with caching](<http://channel9.msdn.com/shows/ARCast.TV/ARCastTV-Scott-Hanselman-on-scaling-websites-with-caching/ >)，主要是介紹 “[Velocity](http://msdn.microsoft.com/en-us/data/cc655792.aspx)”這套產品，如果 Cache 用很多且 Cache 量很大的人，可以開始專注這套產品，除了強調高效能外，也十分強調管理性，讓多台主機同時負責記憶體快取(Memory Cache)的任務。

**相關連結**

-   [HttpRuntime.Cache 屬性](http://msdn.microsoft.com/zh-tw/library/system.web.httpruntime.cache.aspx)
-   [Microsoft Project Code Named "Velocity"](http://msdn.microsoft.com/en-us/data/cc655792.aspx)
