Asp.net Cache

原文链接:http://www.codeproject.com/KB/aspnet/AspDotNetCache.aspx

Introduction

Caching is a technique of storing data in memory which takes time to create. Caching is the one of the best feature of the Asp.Net. For example you could cache the data from complex query which takes time to fetch data. The subsequent requests would not need to fetch data from data base. You can get data directly from the cache. By using the cache you can improve the performance of your application.

There are two main types of caching.

  1. Output caching
  2. Data caching

1. Output Caching

By using Output cache, you can cache the final rendered html of the page. When the same page is requested again, the cached page is served. ASP.Net does not start the page life cycle and does not execute the code. The syntax of Output cache is

Collapse Copy Code
 <%@ OutputCache Duration=”60” VaryByParam=”None”  %> 

Duration attribute sets that page will be cached for 60 second. If any user requests the page first Asp.net runs the page code and sends the rendered html to user and also saves it to the cache. If server receives a request of same page within 60 seconds, ASP.NET automatically sends the cached copy page. If Server receives a request after the expiration of cached page, ASP.NET runs page code again and creates a new cached copy of HTML output for next 60 seconds.

Collapse Copy Code
 <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
        CodeFile="OutputCachingTest.aspx.cs" Inherits="OutputCachingTest" Title="Untitled Page" %>

 <%@ OutputCache Duration="20" VaryByParam="None" %>

 <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
 
   <div class="title">Output Cache</div>
   Date: <asp:Label ID="lblDate" runat="server" Text="" />
   Time: <asp:Label ID="lblTime" runat="server" Text="" /> 
      
 </asp:Content>
Collapse Copy Code
 protected void Page_Load(object sender, EventArgs e)
 {
    lblDate.Text = DateTime.Now.ToShortDateString();
    lblTime.Text = DateTime.Now.ToLongTimeString(); 
 } 

In this example page will be cached for 20 seconds.

Cache by Query String

In real word scenario, Dynamic page changes their contents according to some parameters. If your page is receiving information through query string, you can easily cache different copies of page according to query string. VarByParam=”None” tells ASP.NET to store one copy of the cached page. VarByParam=”*” tells ASP.NET to store Separate copy of the page for different query string parameters.

Collapse Copy Code
 <%@ OutputCache Duration="60" VaryByParam="*" %>
 
 <div align="right">
   <a href="OutputCachingTest2.aspx">No Query String</a> | 
   <a href="OutputCachingTest2.aspx?id=1">ID 1</a> | 
   <a href="OutputCachingTest2.aspx?id=2">ID 2</a> | 
   <a href="OutputCachingTest2.aspx?id=3">ID 3</a> |
   <a href="OutputCachingTest2.aspx?id=3&langid=1">ID 3</a>
 </div> 

In sample project I am passing different “ID” in query string. ASP.NET stores separate copy for each “ID” and this technique is good in this scenario. But this technique has some problems, if page is accepting wide range of different query string. In this case ASP.NET caches separate copy of page according to query string parameters and potentially low the reusability. In this case you can specify important query string variable names in VarByParam attribute.

Collapse Copy Code
 <%@ OutputCache Duration="60" VaryByParam="id;langid" %>

In this case, ASP.NET caches separate version differs by “id” or “langid”.

Custom Caching

You can also create your own custom procedure to cache page. ASP.NET provides a way to create custom cache easily. Use VarByCustom attribute to specify the name that represents the type of custom cache you are creating.

Collapse Copy Code
 <%@ OutputCache Duration="20" VaryByParam="None" VaryByCustom="browser" %>

You also need to create method that will generate custom string for cache. Syntax of the method is

Collapse Copy Code
 public override string GetVaryByCustomString(HttpContext context, string custom)
 {
 
    if (custom == "browser")
    {
       return context.Request.Browser.Browser +
              context.Request.Browser.MajorVersion;
    }
    else
    {
       return base.GetVaryByCustomString(context, custom);
    }
 }

This method must be coded in the global.asax file. This method return string value and ASP.NET uses this string to implement caching. If this method return same string for different requests, ASP.NET reuses cached page otherwise ASP.NET generates a new cached version.

In our above example GetVaryByCustomString() creates a cache string based on browser name. ASP.NET will create a different version of cache for different browser requests.

Control Cache

In above caching technique you can cache the complete page easily but if you want to cache the contents of specific control, you can achieve this feature by using VaryByControl attribute you can cache a control.

Collapse Copy Code
 <%@ OutputCache Duration="20" VaryByControl="MyControl_1" %>

By adding this line on .aspx page, ASP.NET will cache MyControl_1 for 20 min. In this scenario ASP.NET creates one cached version of the “MyControl_1” and if cache is not expire Asp.NET reuse cached version otherwise it execute controls code again.

If you want to cache the control depending on some property value, ASP.NET also provides you this facility. Just add OutPutCache directive in the *.ascx page.

Collapse Copy Code
 <%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyControl.ascx.cs" Inherits="Controls_MyControl" %>
 <%@ OutputCache Duration="20" VaryByControl="EmployeeID" %>
 ......
 ...... 

VaryByControl=”EmployeeID” tells ASP.NET to create different version of the control depend on the EmployeeID property declared in control.

Add EmplyeeID property in .ascx.cs file which will be used by ASP.NET for cache.

Collapse Copy Code
 private int _employeeID;

 public int EmployeeID
 {
   get { return _employeeID; }
   set { _employeeID = value; }
 }

 protected void Page_Load(object sender, EventArgs e)
 {
   lblDate.Text = DateTime.Now.ToShortDateString();
   lblTime.Text = DateTime.Now.ToLongTimeString();

   lblEmployeeID.Text = EmployeeID.ToString();

 }

Add control on the page and set EmployeeID.

Collapse Copy Code
 <%@ Register Src="Controls/MyControl.ascx" TagName="MyControl" TagPrefix="uc1" %>
 <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div align="center">
        <uc1:MyControl ID="MyControl1" runat="server" EmployeeID="1"></uc1:MyControl>
    </div>
 </asp:Content>

Cache Profile

Asp.Net also provides you a facility to define cache settings in the web.config. Suppose if you embed cache setting in to the page and you want to change cache duration from 20 to 30 seconds, then you needs to change duration in all pages. It is better to save cache setting in web.config and you can easily manage your cache setting.

Collapse Copy Code
<system.web>
  <caching>
    <outputCacheSettings >
      <outputCacheProfiles>
	    <add name ="ProductItemCacheProfile" duration ="60"/>
	  </outputCacheProfiles>
	 </outputCacheSettings>
   </caching>
 </system.web>

Now you can use this profile in page using CacheProfile=”ProfileName” attribute.

Collapse Copy Code
 <%@ OutputCache CacheProfile ="ProductItemCacheProfile" VaryByParam="None" %>

2. Data Caching

ASP.NET also provides you flexible type of caching called data cache. You add items which are expensive to create in a collection object cache. Cache is a key, value pair collection, you can add item in to cache collection just by assigning a new key name.

Collapse Copy Code
 Cache["Name"] = data;

This technique does not provide control over cache object. Use Cache.Insert() method which provides five version of methods. By using Insert method you can set cache expiration policy, Priority, Dependencies etc.

Collapse Copy Code
 date1 = DateTime.Now;
 Cache.Insert("Date1", date1, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero);

ASP.NET allows you to set an absolute expiration or sliding expiration policy, but you can use only one at the same time.

Cache dependency

You can also set Cache dependency in ASP.NET. Cache Dependencies you to make a cached item dependent on another resource, so that when that resource changes, the cached item is removed automatically. CacheDependency class is used for creating dependency. This class has many constructor versions. You can create dependency on file or folder. If that file or folder will change, the cache will be expired. You cache dependency on other cache item.

Collapse Copy Code
 date2 = DateTime.Now;

 string[] cacheKeys = { "Date1" };
 CacheDependency cacheDepn = new CacheDependency(null, cacheKeys);
 Cache.Insert("Date2", date2, cacheDepn);

In this example “Date2” cache object is depends on the “Date1” cache item. When “Date1” object will expire then “Date2” will automatically expire. In CacheDependency(null, cacheKeys) constrcutor first parameter is 'null' because we are not creating cache having file/folder dependency. We only passed keys list of cached item, because we want to create item cache dependency.

Callback Method and Cache Priority

ASP.NET also allows you to write a callback method that will be triggered when cached item is removed from the cache. You can also set the priority of the cached item.

Collapse Copy Code
 protected void Page_Load(object sender, EventArgs e)
 {
   DateTime? date1 = (DateTime?)Cache["Date1"];
   if (!date1.HasValue) // date1 == null
   {
     date1 = DateTime.Now;
     Cache.Insert("Date1", date1, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero, 
                  CacheItemPriority.Default, new CacheItemRemovedCallback(CachedItemRemoveCallBack));
   }

   DateTime? date2 = (DateTime?)Cache["Date2"];
   if (!date2.HasValue) // date2 == null
   {
     date2 = DateTime.Now;
     Cache.Insert("Date2", date2, null, DateTime.Now.AddSeconds(40), TimeSpan.Zero, 
                  CacheItemPriority.Default, new CacheItemRemovedCallback(CachedItemRemoveCallBack));
   }

   // Set values in labels
   lblDate.Text = date1.Value.ToShortDateString();
   lblTime.Text = date1.Value.ToLongTimeString();

   lblDate1.Text = date2.Value.ToShortDateString();
   lblTime1.Text = date2.Value.ToLongTimeString();

 }
    
 private void CachedItemRemoveCallBack(string key, object value, CacheItemRemovedReason reason)
 {
   if (key == "Date1" || key == "Date2")
   { 
      Cache.Remove("Date1");
      Cache.Remove("Date2");
   }
 }

As you can see in example, I created “Date1” & “Date2” cache. “Date1” expiry Duration in 20 second and “Date2” has 40 second but you will notice that both expiries together, the reason is because we I have registered remove callback method. When “Date1” or “Date2” expires it calls CachedItemRemoveCallBack method. In this method I remove both the cached item.

ASP.Net also provides you a facility to handle update callback handler for cached item. CacheItemUpdateCallback delegate event uses for this purpose.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shakeel Iqbali have been working in software house as senior software engineer. i have worked on many web and windows projects. My hobbies are to read books and develop my own small utilities.
Occupation: Software Developer (Senior)
Company: TEO
Location: Pakistan Pakistan
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值