zoukankan      html  css  js  c++  java
  • 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对象。

  • 相关阅读:
    ubuntu18.04安装ssh服务
    跳转
    【WinForm】—窗体之间传值的几种方式
    使用jQuery完成复选框的全选和全不选
    VS2015下载安装随笔记录
    关于c#数据类型,类型转换,变量,常量,转义符。
    浅谈表单同步提交和异步提交
    form表单提交和跳转
    2019年8月19日矩阵
    C# WinForm快捷键设置技巧
  • 原文地址:https://www.cnblogs.com/ChengWenHao/p/AspNetPart7.html
Copyright © 2011-2022 走看看