Use the HTTP Cache to improve performance in ASP.NET web pages
In ASP.NET web pages performance is always a factor. If your page displays
static data that doesn't change often, you can cache it instead of
retrieveing it from a database every time the page loads.
Say you have a page that contains a dozen DropDownList controls that get
populated from a database each time the page is requested. This requires a
dozen trips to the database just to load the dropdowns not to mention the
overhead of retrieving the page's core content. Of course, you only need to
populate the dropdowns on initial page loads and not on postbacks (i.e. when
Page.IsPostBack is False).
However, you can dramatically increase performance by not going to the database
at all. You do this through caching. An application's Cache
object lets you store and retrieve arbitrary data on subsequent requests. The
cache is not associated with a page or user session. It is used to enhance
application performance by storing its contents in the web server's memory. It
is implemented by the Cache class, with instances
private to each application, and its lifetime is tied to that of the
application
.NET makes caching easy by using the System.Web.Caching
namespace. You can access the cache by using the Cache property of the
Page object or the HttpContext object
as I do here.
Looking at MSDN you will see many methods and properties associated with the
cache object. I will show only basics here. You can even get fancy and use callbacks
to see when a cached item has changed.
Here are two VB.NET routines. One adds an item to the cache and one retrieves
it. The cache works like a collection with key value pairs. AddToCache adds
an item to the cache via the HttpContext.Current.Cache.Insert
method. This method has several overloads. As used here it requires a key, the
data to cache, an indicator (Nothing) specifying what the cached data
depends on, an absolute timeout period after which the item will be removed (DateTime.MaxValue),
and a rolling timeout (20 minute).
These methods conditionally use the cache based on a setting in the web.config
file. This is useful so users get the benefits of caching but as a developer
you can disable caching to verify your data retrival logic.
Sample VB.NET routines to add and retrieve an item to/from the HTTP cache.
Public Sub AddToCache(ByVal strKey As String, ByVal objValue As Object)
'
'Set the amount of time before the cache expires.
'
Dim TimeSpanToUse As Double = 20.0
Dim blnCacheEnabled As Boolean = _
Convert.ToBoolean(ConfigurationSettings.AppSettings("CacheEnabled").Trim())
If blnCacheEnabled Then
HttpContext.Current.Cache.Insert(strKey, objValue, Nothing, _
DateTime.MaxValue, TimeSpan.FromMinutes(TimeSpanToUse))
End If
End Sub
Public Shared Function GetFromCache(ByVal strKey As String) As Object
Dim blnCacheEnabled As Boolean = _
Convert.ToBoolean(ConfigurationSettings.AppSettings("CacheEnabled").Trim())
If blnCacheEnabled Then
Return HttpContext.Current.Cache.Get(strKey)
Else
Return Nothing
End If
End Function
The following routine is a wrapper which is called once for each DropDownList to
populate on your web page. It can be called in the Page_Load
event when Page.IsPostBack is False.
VB.NET routine to populate a DropDownList control from the cache.
Public Shared Sub GetLookupValues(ByRef lc As DropDownList, ByVal CodeType As Integer)
Dim ds As DataSet
'
' Build the unique key.
'
Dim strKey As String = "Lookup.Values." & CodeType.ToString()
'
' Get the cached dataset.
'
Dim obj As Object = GetFromCache(strKey)
'
' If nothing was cached, read from the database by calling
' your data access layer to issue SQL similar to:
'
' "Select code,description from LookupValues " & _
' "Where code_type =" & CodeType .ToString
'
If obj Is Nothing Then
'
' Read the database and cache the results for next time.
'
ds = ... DAL.GetLookupValues(CodeType)
AddToCache(strKey, ds)
Else
'
' Cast the cached object back to a DataSet.
'
ds = DirectCast(obj, DataSet)
End If
'
' Bind the dataset to the DropDownList control.
'
lc.DataSource = ds
lc.DataValueField = "CODE"
lc.DataTextField = "DESCRIPTION"
lc.DataBind()
End Sub
|