上一篇:VML应用 >>
Caching in ASP.NET
To overcome this, some websites have page creation engines which create all pages in one go and save them as HTML pages which are then served to the users. But this will only help in scenarios where the page content is the same for all requests [user-independent] as in the second example above. The listing of books is the same irrespective of the user requesting the page. Even if there is provision for listing books category wise by providing different category ID values through the querystring, the page output for a particular category of books is the same for all users.
ASP.NET provides support for "caching" which will help us solve this problem to a great extend. It can cache [store in memory] the output generated by a page and will serve this cached content for future requests. And this is useful only in the second scenario described earlier, where the page content is the same for all requests [user-independent]. The caching feature is customizable in various ways and we will see how we can do that as we go through this article.
Caching a page
In order to cache a page‘’s output, we need to specify an @OutputCache directive at the top of the page. The syntax is as shown below:
<%@ OutputCache Duration=5 VaryByParam="None" %>
As you can see, there are two attributes to this directive. They are:
Duration - The time in seconds of how long the output should be cached. After the specified duration has elapsed, the cached output will be removed and page content generated for the next request. That output will again be cached for 10 seconds and the process repeats.
VaryByParam - This attribute is compulsory and specifies the querystring parameters to vary the cache.
In the above snippet, we have specified the VaryByParam attribute as None which means the page content to be served is the same regardless of the parameters passed through the querystring [see Example 1 in the sample download].
If there are two requests to the same page with varying querystring parameters, e.g.: .../PageCachingByParam.aspx?id=12 and .../PageCachingByParam.aspx?id=15] and separate page content is generated for each of them, the directive should be:
<%@ OutputCache Duration=5 VaryByParam="id" %>
The page content for the two requests will each be cached for the time specified by the Duration attribute [see Example 2 in the sample download].
To specify multiple parameters, use semicolon to separate the parameter names. If we specify the VaryByParam attribute as *, the cached content is varied for all parameters passed through the querystring.
Some pages generate different content for different browsers. In such cases, there is provision to vary the cached output for different browsers. The @OutputCache directive has to be modified to:
<%@ OutputCache Duration=5 VaryByParam="id" VaryByCustom="browser" %>
This will vary the cached output not only for the browser but also its major version. I.e., IE5, IE 6, Netscape 4, Netscape 6 will all get different cached versions of the output.
Caching page fragments
Sometimes we might want to cache just portions of a page. For example, we might have a header for our page which will have the same content for all users. There might be some text/image in the header which might change everyday. In that case, we will want to cache this header for a duration of a day.
The solution is to put the header contents into a user control and then specify that the user control content should be cached. This technique is called fragment caching.
To specify that a user control should be cached, we use the @OutputCache directive just like we used it for the page.
<%@ OutputCache Duration=10 VaryByParam="None" %>
With the above directive, the user control content will be cached for the time specified by the Duration attribute [10 secs]. Regardless of the querystring parameters and browser type and/or version, the same cached output is served. [See Example 3 in the download for a demonstration].
Data Caching
ASP.NET also supports caching of data as objects. We can store objects in memory and use them across various pages in our application. This feature is implemented using the Cache class. This cache has a lifetime equivalent to that of the application. Objects can be stored as name value pairs in the cache. A string value can be inserted into the cache as follows:
Cache["name"]="Smitha";
The stored string value can be retrieved like this:
if (Cache["name"] != null) Label1.Text= Cache["name"].ToString();
[See example 4 for an illustration.]
To insert objects into the cache, the Add method or different versions of the Insert method of the Cache class can be used. These methods allow us to use the more powerful features provided by the Cache class. One of the overloads of the Insert method is used as follows:
Cache.Insert("Name", strName, new CacheDependency(Server.MapPath("name.txt"), DateTime.Now.AddMinutes(2), TimeSpan.Zero);
The first two parameters are the key and the object to be inserted. The third parameter is of type CacheDependency and helps us set a dependency of this value to the file named name.txt. So whenever this file changes, the value in the cache is removed. We can specify null to indicate no dependency. The fourth parameter specifies the time at which the value should be removed from cache. [See example 5 for an illustration.] The last parameter is the sliding expiration parameter which shows the time interval after which the item is to be removed from the cache after its last accessed time.
The cache automatically removes the least used items from memory, when system memory becomes low. This process is called scavenging. We can specify priority values for items we add to the cache so that some items are given more priority than others:
Cache.Insert("Name", strName, new CacheDependency(Server.MapPath("name.txt"), DateTime.Now.AddMinutes(2), TimeSpan.Zero, CacheItemPriority.High, null);
The CacheItemPriority enumeration has members to set various priority values. The CacheItemPriority.High assigns a priority level to an item so that the item is least likely to be deleted from the cache.
Points of interest
If there are old ASP pages in your website which use the Response.Expires property to cache page output, they can be retained as such. ASP.NET supports this property as well.
The Insert method of the Cache class will overwrite any existing item with the same key name.
The CacheItemPriority.NotRemovable priority value can be used with Cache.Insert method to set the priority level of an item so that the item will not be removed from the cache during scavenging.
Conclusion
In this article, I have tried to provide an overview of the various options available for caching in ASP.NET. Elaborate explanations and details have not been provided to keep the article short.
Fragment caching can be done in a nested fashion with child controls having caching enabled. How to do this has not been covered as I have not tried it out myself. So also various overloads of the Insert method of the Cache class has not been discussed here. I hope this article will be a good starting point for the readers to explore into the details of a wonderful feature available in ASP.NET.
下一篇:asp论坛在线人数统计研究 >>
相关文章:
- · override deal with window closing in database application
- · C++ 和 Delphi 的函数覆盖(Override)与重载(overload
- · 正确处理ASP动态网页中的容错机制
- · 几例在ASP存储过程的使用方法
- · 实现让每句话的头一个字母都大写
- · 如何尽快释放掉Connection对象建立的连接?
- · Connection对象的应用
- · 利用ASP打造网站论坛DIY
- · Asp中代码与页面的分离
- · 一个ASP版的图片浏览管理器
- · 实现有管理功能的ASP留言板
- · 编译asp应用程序成为exe文件
- · 如何准确定时运行ASP文件
- · ASP整合的一个SQL语句类
- · Jmail发信的实例,模块化随时调用
- · ASP字数计算函数
- · 无刷新随时取得用户当前活动信息
- · ASP自定义函数,仿VBA中域函数DLookup
- · asp中对ip进行过滤限制函数
- · 让ASP程序运行于非Windows平台
- · ASP中实现文件上传方法的研究
- · asp国标转大五码
- · Global.asa文件用法大全
- · 微软建议的ASP性能优化28条守则
- · 在ASP中取得服务器网卡的MAC地址、DNS地址等网络信息
- · ASP中记录的分页
- · 下载网页中的所有资源
- · 函数方便制作管理界面
- · 无限级目录树+记忆节点状态
- · 利用C#在SQL Server2000存取图像 For Window
- · 通过MSXML2自动获取QQ个人头像及在线情况(给初学者)
- · ASP模板类[实现一维循环和二维循环,可以从文件、数据库、变量取摸板]
- · 各种存储过程使用指南
- · 树型结构在ASP中的简单解决
- · 用ASPJPEG组件制作图片的缩略图和加水印
- · 用asp制作强大的搜索引擎(一)
- · VBscript和javascript的选择
- · 在ASP中使用SQL语句之2:用WHERE子句设置查询条件
