Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ASP .NET Web Developer s Guide - Mesbah Ahmed, Chris Garrett

.pdf
Скачиваний:
37
Добавлен:
24.05.2014
Размер:
7.32 Mб
Скачать

290 Chapter 6 • Optimizing Caching Methods

CacheItemRemovedCallback delegate returns three parameters that must be accepted by your event handler: the cached item’s key, the value of the cached item when it was removed, and the reason for removal.There are four valid reasons for an object to be removed from the cache, and they are outlined in Table 6.7.

Table 6.7 CacheItemRemovedReason Values

Reason

Definition

 

 

DependencyChanged

When the files, directories, or keys specified in the

 

dependency option are changed, this reason is

 

reported upon the cached object’s removal.

Expired

If an expiration policy is set for a cached object, this

 

reason is reported when the absolute expiration time

 

has been met.

Removed

If a cached object is explicitly removed or replaced

 

due to the usage of the same key, this reason is

 

reported.

Underused

If ASP.NET has removed the cached object due to a

 

lack of system resources or because the data is under-

 

utilized, the Underused reason is reported.

I have illustrated the use of all the caching options available for the cache.add and cache.insert methods in the code shown in Figure 6.14. In this code, we first check to see if there is any data stored in the cache under the key “MyKey.” If data is there, then note that the data was retrieved from cache, remove the data from the cache, and display the data. If no data is in the cache, then your array is loaded into the cache.When you do remove the cached data, you fire an event that adds the fact that the data was removed from cache as well as the reason code to the array, and then recache the result.When you recache it the second time, you do not add the CacheItemRemoved option; otherwise you would end up in a loop.This code is located on the CD that accompanies this book as data_cache3.aspx.

Figure 6.14 Data Caching Full Sample Code (data_cache3.aspx)

<SCRIPT language="VB" runat=server>

Private Shared OnRemove as CacheItemRemovedCallback = Nothing

Public Sub RemovedCallback(key as string, value as object, _

Continued

www.syngress.com

Optimizing Caching Methods • Chapter 6

291

Figure 6.14 Continued

reason as CacheItemRemovedReason)

'At this point, place any code needing to be executed upon 'an item's removal. As an example, we will now recache the 'object after making a change.

value=value & " *recached due to reason code " & reason & "*<br>" cache.insert(key, value, nothing, datetime.maxvalue, _

timespan.fromseconds(10)) End Sub 'RemovedCallback

Sub Page_Load(source As Object, e As EventArgs) onRemove = New CacheItemRemovedCallback(AddressOf _

Me.RemovedCallback)

dim MyValue as string MyValue=cache("MyKey")

if MyValue <> nothing then

output.text=MyValue & "<P>This data retrieved from cache" 'Now we'll remove the item from cache, just to trigger the

event'

Cache.Remove("MyKey") else

Dim StringArray() As string ={"Amy", "Bob", "Chris", "Damien",

_

"Eli", "Franklin", "Gerald"}

dim DependentString() as string ={server.mappath("test.txt"), _ server.mappath("test2.txt")}

dim MyString as string

for each MyString in StringArray output.Text=output.Text & MyString & "<br>"

next

cache.insert("MyKey", output.text, nothing, datetime.maxvalue, _ timespan.fromseconds(10), CacheItemPriority.Low, _

Continued

www.syngress.com

292 Chapter 6 • Optimizing Caching Methods

Figure 6.14 Continued

CacheItemPriorityDecay.Fast, onRemove)

end if End Sub </SCRIPT>

<HTML>

<HEAD>

</HEAD>

<BODY>

<P><asp:label id="output" runat="server"/> </BODY>

</HTML>Using the Cache.Remove Method

Removing data manually from the cache is a useful method of clearing up resources or giving your end user the option of verifying that the data they are viewing is up to date.The way this is done is similar to the simple dictionary cache interface. I have used the cache.remove method in Figure 6.14, which illustrates its syntax:

cache.remove("MyKey")

Advantages of Using Data Caching

We have gone over the plethora of different options available for data caching, and I believe that its many advantages are apparent.With the ability of caching data at the object level, you are given the most granular control over ASP.NET’s caching features possible. By using the dictionary interface, you have a simple manner of adding and removing data from the cache. If, however, a greater amount of control is necessary, ASP.NET provides for this with the expiration features and priority levels.

By using all of these features in the best manner possible, you can increase the overall speed of your application without the requirements of using a separate user control or a semi-static page.While data caching does take up more memory per saved object than object or fragment caching, its primary strength is that you

www.syngress.com

Optimizing Caching Methods • Chapter 6

293

can store smaller amounts of data in the cache, thus opening the possibility of saving memory resources overall.

Debugging…

Implementing Caching

When building your Web application, it is best to not implement caching on the initial build. There are several reasons for this, the primary being ease of debugging. You will find that it is much easier to get an application completely debugged without having to deal with the question of cached pages and data. When you have the application debugged, begin adding in the caching features of ASP.NET where they are most effective. You will see an immediate performance increase in your application, as well as make your debugging process much faster by following this process.

A second advantage of this method is that you have an opportunity to set a baseline for your application. As memory resources on the server become scarce, cached data is dumped in order to conserve resources. With this baseline performance data, you can provide a worst-case scenario for your application.

Best Uses for Caching

When should you use caching? As often as possible. In order to make your application viable in today’s fast-paced world, you have to make your data available as quickly as possible and decrease the wait-time for your end user as much as possible. By using the various types of caching in the best manner possible, you can change your application from slow yet effective to fast and amazing.When users access an application created using ASP.NET’s caching features for the first time, the first thing they will notice is the speed increase. In the overall user experience, this is one of the most important impressions that you can make. In the following section, I’ve listed several of the best uses for the different methods of caching.

www.syngress.com

294 Chapter 6 • Optimizing Caching Methods

Output Caching

Output caching is best used when an entire page needs to be cached. Examples are as follows:

A semi-static page with data pulled from multiple locations where the

data is known not to change too frequently, such as a message board.

A page that tends to take a long time to load due to its size and complexity.

A page accessed very frequently even if it contains no dynamic data.

Fragment Caching

You can use fragment caching when only some portions of a page need to be cached and other portions of the same page do not. Examples are as follows:

Any page that remains mostly static, with the exception of some data

pulls, should have those data pulls loaded into a user control and cached.

A page that must be constantly updated, with the exception of some

areas, should have those areas loaded into a user control and cached.

Any data accessed frequently between multiple pages within an application can be loaded into a user control and cached so that any page can access the cached data.

Data Caching

Data caching is best used for caching data at the object level. Examples are as follows:

Any page too dynamic for output or fragment caching should have data caching implemented where possible.

An application with objects that tend to be slow-loading should be cached on first use and used from the cache thereafter.

Objects frequently accessed from multiple pages within an application should be cached for simple access from any page in the application.

www.syngress.com

Optimizing Caching Methods • Chapter 6

295

Summary

High performance is one of the most important aspects of any Web application. With the use of ASP.NET’s caching features, you can dramatically increase the performance of your application. Any application can benefit from the use of the caching features; by using the correct types of caching in the correct locations, you can optimize these benefits.

Output caching is used to cache entire pages. It is accessed either through the @ OutputCache directive or programmatically through the HttpCachePolicy cache. By setting the duration option, you can control the length of time that your page is stored in the cache.The additional features provided by the use of the

VaryByParam, VaryByHeader, and VaryByCustom parameters enable you to control the various versions of your page that are stored in the cache.

Fragment caching is used to cache portions of pages when an entire page is unable to be cached, or in a situation where caching the entire page is inefficient. Fragment caching is used by breaking out portions of your code into user controls and including the @ OutputCache directive at the top of your user control. You can also use the HttpCachePolicy to access the features of fragment caching. The parameter of VaryByControl is included, in addition to VaryByParam, to give you control over the versions of the user control stored in the cache.

Data caching is the lowest level of caching available and enables you to cache data at the object level.Three methods are used to call the data caching functions. The first is the cache method, which is used in the same method that you would use a dictionary.There are no additional options available when using data caching with this method.The second and third methods are cache.add and cache.insert.The syntax and usage of these two methods are identical, and the difference between the two is that cache.add returns an object.

Accessing data caching by using the cache.add and cache.insert methods provides you with several options to control the cached data.The first option is the specification of files, directories, and other cache keys that the cached object is dependent upon.The second option is the use of two methods to specify the length of time that the object is stored in the cache.The third is the setting of priority levels for your cached data. By using priority levels, you control the order in which cached data is removed when ASP.NET purges the cache due to a lack of memory resources or infrequent access.The final option is the ability to specify a callback delegate when the object is removed from cache.The reason the object was removed from the cache as well as the value of the object at the time it was removed are specified to the callback delegate, and you can take any actions necessary based on this information.

www.syngress.com

296 Chapter 6 • Optimizing Caching Methods

Solutions Fast Track

Caching Overview

;Caching is used to increase performance of your Web application. It does this by storing frequently accessed data in memory.

;ASP.NET provides three different types of caching: output caching, fragment caching, and data caching.

;The proper balance of caching and usage of system resources is key to increasing overall application performance.

Output Caching

;Output caching caches an entire page, and you can cache multiple versions of the page by the use of available parameters.

;Output caching is accessed through either the @ OutputCache directive or the HttpCachePolicy class.

;The options to control data stored with output caching are:

VaryByParam,VaryByHeader, and VaryByCustom.

Fragment Caching

;Fragment caching caches a portion of a page.This is done by breaking your code out into user controls and caching the control.

;Fragment caching enables you to take advantage of caching features when you are unable to cache the entire page.

;The options to control data stored with fragment caching are:

VaryByParam and VaryByControl.

Data Caching

;Data caching caches individual objects.

;There are three methods of putting data into the data cache: cache, cache.add and cache.insert.

www.syngress.com

Optimizing Caching Methods • Chapter 6

297

;Using the cache.add and cache.insert methods provide you with options to control cached data based on dependencies, duration, and priority as well as specifying a callback delegate.

Best Uses for Caching

;Use caching whenever possible to increase the performance of your application.

;Keep in mind the tradeoff between system memory resources and the caching of data when planning your caching policy.

;Use the correct type of caching at the correct points in your application for the highest performance increase possible.

Frequently Asked Questions

The following Frequently Asked Questions, answered by the authors of this book, are designed to both measure your understanding of the concepts presented in this chapter and to assist you with real-life implementation of these concepts. To have your questions about this chapter answered by the author, browse to www.syngress.com/solutions and click on the “Ask the Author” form.

Q:I have been asked to migrate an application from ASP to ASP.NET. In the ASP application, several third-party utilities have been used to provide for caching. Should I use these or use ASP.NET’s internal caching?

A:Use ASP.NET’s caching when possible.With automatic scavenging features and integrated memory management, ASP.NET provides a more tightly integrated caching system than existing third-party utilities.

Q:Within my application, there is a table populated with data from several different databases. How could I best implement caching in order to share this populated table between multiple pages of my application?

A:Use fragment caching to cache a user control that builds your table. Items stored in the cache are accessible throughout the application.

Q:I am concerned about the use of memory on my server. Prior to implementing caching, the memory utilization of the system was fairly low, but

www.syngress.com

298 Chapter 6 • Optimizing Caching Methods

after adding the caching features to every page of my application, the memory utilization has gone up quite a bit. Is it possible to add so many items to the cache that I begin to run into a lack of memory resources?

A:This is possible if all of your items are cached using data caching with the parameters set to never remove the data from cache. However, by caching any data without this parameter opens the cached data up to be removed from the cache if the system becomes low on resources.

Q: Which is the overall best method of caching?

A:There is no “best” method. Each of the different caching options apply under different circumstances, and all of them provide an overall application performance increase when used properly.

www.syngress.com

Chapter 7

Introduction to

ADO.NET: A Simple

Address Book

Solutions in this chapter:

Understanding the Changes in ADO.NET

Creating Connection Strings

Creating an Address Book Application

;Summary

;Solutions Fast Track

;Frequently Asked Questions

299