1. 程式人生 > >ASP.NET -- WebForm -- 快取Cache的使用

ASP.NET -- WebForm -- 快取Cache的使用

ASP.NET -- WebForm --  快取Cache的使用

把資料從資料庫或檔案中讀取出來,放在記憶體中,後面的使用者直接從記憶體中取資料,速度快。適用於經常被查詢、但不經常變動的資料。

1. Test5.aspx檔案與Test5.aspx.cs檔案

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test5.aspx.cs" Inherits="Test5" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="LabelCurrentTime" runat="server" Text=""></asp:Label> <asp:Button
ID="Button1" runat="server" Text="新增值至快取" onclick="Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="移除快取" onclick="Button2_Click" /><br /> <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox> </div> </form> </body> </
html>
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        LabelCurrentTime.Text = DateTime.Now.ToLongTimeString();

        if ( Cache["WeekData"]!=null)
        {
            ListBox1.DataSource = Cache["WeekData"];
            ListBox1.DataBind();
        }
        else
        {
            ListBox1.DataSource = null;
            ListBox1.DataBind();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        List<string> list = new List<string>();
        list.Add("星期日");
        list.Add("星期一");
        list.Add("星期二");
        list.Add("星期三");
        list.Add("星期四");
        list.Add("星期五");
        list.Add("星期六");
        Cache["WeekData"] = list;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Cache.Remove("WeekData");
    }
}
View Code

 

2. 使用Cache

(1) 第一次訪問頁面,沒有快取

(2) 新增快取值

(3) 再次訪問頁面,由於快取有值,直接從快取取值

(4) 移除快取值

(5) 再次訪問頁面,由於快取值已被移除,不能從快取中取到資料

 

3. Cache中的資料是大家共享的,與Session不同。Session --> 每個使用者都有自己的Session物件。