简单的实例,cache方法理解ASP.NET缓存 Cache之数据缓存
大家可以通过各种各样的方法去优化我们系统,本篇博文将介绍通过Cache方法来优化系统的性能,减轻系统的负担。
- <%@ Page Language="VB" AutoEventWireup="false" CodeFile="cache.aspx.vb" Inherits="admin_cache" %>
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <input type=submit OnServerClick="AddItemToCache" value="Add Item To Cache" runat="server"/>
- <input type=submit OnServerClick="RemoveItemFromCache" value="Remove Item From Cache" runat="server"/>
- </div>
- </form>
- </body>
- </html>
- Imports System.Web.Caching
- Partial Class admin_cache
- Inherits System.Web.UI.Page
- Shared itemRemoved As Boolean = False
- Shared reason As CacheItemRemovedReason
- Dim onRemove As CacheItemRemovedCallback
- Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
- '缓存技术,首先判断是否有缓存数据
- If (itemRemoved) Then
- Response.Write("RemovedCallback event raised.")
- Response.Write("<BR>")
- Response.Write("Reason: <B>" + reason.ToString() + "</B>")
- Else
- Response.Write("Value of cache key: <B>" + Server.HtmlEncode(CType(Cache("Key1"), String)) + "</B>")
- End If
- End Sub
- Public Sub RemovedCallback(k As String, v As Object, r As CacheItemRemovedReason)
- itemRemoved = True
- reason = r
- End Sub
- Public Sub AddItemToCache(sender As Object, e As EventArgs)
- '添加缓存数据,同时触发onRemove事件,itemRemoved变成真
- onRemove = New CacheItemRemovedCallback(AddressOf Me.RemovedCallback)
- If (IsNothing(Cache("Key1"))) Then
- Cache.Add("Key1", "这里是缓存数据", Nothing, DateTime.Now.AddSeconds(10), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove)
- End If
- End Sub
- Public Sub RemoveItemFromCache(sender As Object, e As EventArgs)
- '移除缓存数据
- If (Not IsNothing(Cache("Key1"))) Then
- Cache.Remove("Key1")
- End If
- End Sub
- End Class