Web caching in ASP.NET 2.0 (VB.NET)
See more tutorials in Network. This post has Comments Off on Web caching in ASP.NET 2.0 (VB.NET).
Web caching technology in ASP.NET and VB.NET is helpful for popular website reducing its server workload and improving access times. This tutorial will show you how to use web caching save data to RAM, and improve data access times therefore.
First, import the namespace of System.Web.Caching
0 1 2 |
import System.Web.Caching |
Declare the variables
0 1 2 3 4 |
Shared itemRemoved As Boolean = False Shared reason As CacheItemRemovedReason Dim onRemove As CacheItemRemovedCallback |
Define the method of AddItemToCache, it will use Cache.Add to add items to cache
0 1 2 3 4 5 6 7 8 9 10 |
Public Sub AddItemToCache(ByVal sender As Object, ByVal e As EventArgs) Handles Submit1.ServerClick itemRemoved = False onRemove = New CacheItemRemovedCallback(AddressOf Me.RemovedCallback) If (IsNothing(Cache("Key1"))) Then Cache.Add("Key1", "Caching", Nothing, DateTime.Now.AddSeconds(30), TimeSpan.Zero, CacheItemPriority.High, onRemove) End If End Sub |
Define the method of RemoveItemFromCache, it will use Cache.Remove to remove items from cache
0 1 2 3 4 5 6 |
Public Sub RemoveItemFromCache(ByVal sender As Object, ByVal e As EventArgs) Handles Submit2.ServerClick If (Not IsNothing(Cache("Key1"))) Then Cache.Remove("Key1") End If End Sub |
When using the method of Cache.Remove , it will be leaded to invoke RemovedCallback method
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Public Sub RemovedCallback(ByVal k As String, ByVal v As Object, ByVal r As CacheItemRemovedReason) itemRemoved = True reason = r End Sub [vb] Page_Load [vb] Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If (itemRemoved) Then Response.Write("Removed event raised.") Response.Write("<BR>") Response.Write("Reason: <B>" + reason.ToString() + "") Else Response.Write("Value of cache key: <B>" + Server.HtmlEncode(CType(Cache("Key1"), String)) + "</B>") End If End Sub |
The HTML of the web page
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <body> <Form id="Form1" runat="server"> <input id="Submit1" type=submit OnServerClick="AddItemToCache" value="Add Item To Cache" runat="server"/> <input id="Submit2" type=submit OnServerClick="RemoveItemFromCache" value="Remove Item From Cache" runat="server"/> </Form> </body> </html> |