Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Take Advantage of ASP.NET 2.0's Data Caching Techniques, Part 1 : Page 2

This two-part article shows you how to take advantage of the many ways that you can boost the performance of ASP.NET applications by caching the data they use. Although some of the techniques apply to both ASP.NET 1.0 and 2.0, the new capabilities in ASP.NET 2.0 make caching even more attractive for busy Web sites.

The ASP.NET Application, Session and ViewState
You use the Application and Session objects in ASP.NET in essentially the same way as in "classic" ASP, except that you should be aware of data typing issues. It's always a good idea to cast or convert values to the correct type when you extract them. For example:

Dim iThisValue As Integer = 42 Application("MyInteger") = iThisValue Dim iThatValue As Integer = CType( _ Application("MyInteger"), Integer)

In C#, that same code is:

int iThisValue = 42; Application["MyInteger"] = iThisValue; int iThatValue = (int) Application["MyInteger"];

Alternatively, you can use the methods exposed by the HttpApplicationState class (from the System.Web namespace), which is the class used to implement the Application object in ASP.NET. These methods include Add, Clear, Get, Remove, RemoveAt, and Set, plus properties and methods to retrieve information about the keys for the stored items such as AllKeys, Count, GetKey, etc.

Author's Note: See the .NET Framework SDK topic "HttpApplicationState Members" in the "Reference | Class Library" section for more details.

ASP.NET itself uses thread locking to automatically lock the Application (and Session) to prevent concurrent updates to the values stored there from causing inconsistent results; however if you are updating values in the Application you should use the Lock and Unlock methods as in previous versions of ASP:

Application.Lock() Dim iThisValue As Integer = CType( _ Application("MyInteger"), Integer) iThisValue += iMyIncrement Application("MyInteger") = iThisValue Application(UnLock)

You aren't limited to storing only simple intrinsic .NET value types in the Application (or Session). You can store any serializable class instance, for example a DataSet (in version 2.0, the DataTable is also serializable). As an example, this code stores a DataSet in the Application:

Application("MyDataSet") = dsMyData Dim dsRetrievedData As DataSet = _ CType(Application("MyDataSet"), DataSet)

ASP.NET Sessions
The HttpSessionState class (in the System.Web.SessionState namespace) implements ASP.NET's Session object. The Session object has no Lock or Unlock method, though you can use the IsSynchronized and SyncRoot properties to create your own thread-safe implementations if you wish. However, for general use, the Session works just like the Application for reading and storing values.

Remember that the Session exposes some useful properties such as IsCookieless and IsNewSession, which you may find useful. But the most important feature in ASP.NET in terms of improving page execution efficiency is the implementation of read-only sessions. ASP.NET raises a whole series of events as it loads and executes an ASP.NET page, and two of these are concerned with loading and saving Session data. As a page loads, an event causes ASP.NET to search the Session for any values that apply to the page, and load those it finds into the execution memory space for the page. As execution of the page ends, another event causes ASP.NET to write those values back to the Session store.

So it's pretty obvious that you can reduce page execution overheads by avoiding the two event calls if you don't need to read or update session data. And if you only need to read it, but not update it, you can specify read-only access to the Session. To specify that a page does not require access to the user's session, add this directive:

<%@Page EnableSessionState="False" ... %>

To allow your application to read session data but not update it, thus avoiding the expensive process of updating the session data at the end of the page, use this directive:

<%@Page EnableSessionState="ReadOnly" ... %>

Note that there is also a property named IsReadOnly on the HttpSessionState class that you can query in your page code to see if the current session is read-only. You can also specify the session behavior at machine or application level using the <pages> element within the <system.web> section of machine.config or web.config.

</span><pages enableSessionState="[true|false|ReadOnly]" ... />

ASP.NET ViewState
If you need to cache only a single value or a small set of data for an individual page between postbacks, you can use the ASP.NET ViewState. When an ASP.NET page contains a server-side HTML form (a <form> section declared with the runat="server" attribute), it generates an HTML <hidden> control that contains the values of the controls on the page, and other state information, in an encoded format.

You can add values to ViewState and retrieve them using the same approach as with the Application and Session objects:

Dim iThisValue As Integer = 42 Viewstate("MyInteger") = iThisValue Dim iThatValue As Integer = CType( _ Viewstate("MyInteger"), Integer)

In C#, the equivalent code is:

int iThisValue = 42; Viewstate["MyInteger"] = iThisValue; int iThatValue = (int) Viewstate["MyInteger"];

Just bear in mind that your data passes across the network with each page request and each postback, and so this is definitely not an ideal approach for storing large volumes of page-specific data. A better solution is to store some key value in the ViewState, and then use that key to store and retrieve the real data from a database, a disk file, or one of the other types cache better suited to storing large volumes of data.

As with sessions, you can disable the storage of ViewState for a page. ViewState is enabled by default, and even when disabled some control and state information is still persisted. However, there is no concept of a "read-only ViewState." To disable ViewState for the page, use the Page directive:

<%@Page EnableViewState="False" ... %>

To disable ViewState for all the ASP.NET applications on a server or for all the pages in a site, alter your machine.config or web.config files as follows:

<pages enableViewState="false" ... />

Author's Note: See the .NET Framework SDK topic "Saving Web Forms Page Values Using View State" in the "Building Applications | Creating ASP.NET Web Applications" section for more details.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date