Wednesday 22 January 2014

Caching in Asp.Net

                 In this article we are going to see the topic about caching, caching is a technique to store the user request page in the server memory as rendered output html, so when ever user request that particular page, it doesn't generate or rendered the page ,it returns the output of the page from the memory. It is used to Improve the performance of the application.

To cache a webform use the @OutputCache page directive in the page. Duration attribute to specify how many seconds that page would cache.


Now let we take a sample that the default page is cached for 10 seconds and make the user to enter the value in the textbox and in the response it will return back the input typed in the textbox. For example if i submit a value of 2 and submit the form the return value is : Sample Caching Value:- 2





When the user the reenter the value as 3 in the textbox with in the 10 seconds and submit the page, it will return the same page which is cached in server memory.so again it will return the page of value with 2 not 3, because the page with value 2 is cached in server memory for 10 seconds.



After the submit .



Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SampleWebApp._Default" %>
<%@ OutputCache Duration="20" VaryByParam="None" %>
<!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>  
    Testing Caching !   
    <br/ />   
        <br />
        <br />
    Id :- <asp:TextBox runat="server" ID="id"></asp:TextBox>
    <br />   
    <asp:Button runat="server" ID="submit" onclick="submit_Click" Text="Submit" />
    <br />  
        <br />
    <br/ />
     <asp:Label ID="display" runat="server"></asp:Label>
    </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;
using System.Diagnostics;

namespace SampleWebApp
{
    public partial class _Default : System.Web.UI.Page
    {
        private string DbLoad()
        {
            System.Threading.Thread.Sleep(10000);
            return "Sample Caching";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
       
        }

        protected void submit_Click(object sender, EventArgs e)
        {
            Stopwatch watch = Stopwatch.StartNew();
            watch.Start();
            string value = DbLoad();
            display.Text = value + ", Value :-" + id.Text;
        }
    }
}


After the 10 seconds, if the user enters the value as 3 then it will return the value in the response is 3.

From this article you can see what is output cache and there usage in the asp.net 

No comments:

Post a Comment