ASP.NET -- WebForm -- Use of Cache Cache

Keywords: ASP.NET Session Database

ASP.NET -- WebForm -- Use of Cache Cache

Read the data from the database or file, and put it in memory. The latter users get the data directly from the memory, which is fast. Applicable to data that is frequently queried but not frequently changed.

1. Test5.aspx file and Test5.aspx.cs file

<%@ 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="Add value to cache" onclick="Button1_Click" />
        <asp:Button ID="Button2" runat="server" Text="Remove cache" onclick="Button2_Click" /><br />
        <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
    </div>
    </form>
</body>
</html>
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("Sunday");
        list.Add("Monday");
        list.Add("Tuesday");
        list.Add("Wednesday");
        list.Add("Thursday");
        list.Add("Friday");
        list.Add("Saturday");
        Cache["WeekData"] = list;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Cache.Remove("WeekData");
    }
}

 

2. Use Cache

(1) First visit to the page, no caching

(2) Add cached values

(3) Visit the page again and get the value directly from the cache because the cache has value.

(4) Remove cached values

(5) Visit the page again, because the cached value has been removed, the data can not be retrieved from the cache.

 

3. Data in Cache is shared by all, unlike Session. Session - > Each user has its own Session object.

Posted by eabigelow on Tue, 22 Jan 2019 11:30:13 -0800