資料快取

ASP.Net 公開 Cache API 以將資料儲存在快取中以便以後檢索。

入門

儲存字串

   Cache["key"]="value";

檢索字串

var value="";
if (Cache["key"] != null)
   value = Cache["key"].ToString();

你還可以使用“ 新增” 或“ 插入” 方法。

protected void Page_Load( object sender, EventArgs e)
{
    if ( this.IsPostBack )
    {
        label1.Text + = "Page is posted back";
    }
    else
    {
        label1.Text + = "Page is created";
    }
    
    if ( Cache [ "item"] == null )
    {
        label1.Text + = "New item is created";
        DateTime item = DateTime.Now;
        label1.Text + = "Item is stored";
        Cache.Insert ( "item", item, null );
        DateTime.Now.AddSeconds ( 20 ), TimeSpan.Zero;
    }

    else
    {
        label1.Text + = "Item is accesses";
        DateTime item = ( DateTime) Cache [ "item" ];
        label1.Text + = "Time is: " + item.ToString();
        label1.Text + = <br/>";
    }
    
    label1.Text + = "<br/>";
}