DATA CACHING in asp.net with cache class

ASP.Net caching feature stores objects in memory.

By using instance of ‘Cache’ class, we can use this feature. Internally key/value pairs

Unlike sessions, application cache is global (application wide) and every user who accesses that application can access the value in the cache.

Syntax:

Store data in cache

HttpContext.Current.Cache.Insert(key, data)

Retrieve data from cache

HttpContext.Current.Cache(“keyname”)

Clear all cached items

ClearCache(“”)

See one example:

If you set following page load function, then each time you refresh page, you will see same time value each time.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If IsNothing(HttpContext.Current.Cache(“mykey”)) Then

HttpContext.Current.Cache.Insert(“mykey”, “This message was stored in cache at : ” & Date.Now)

End If

Response.Write(HttpContext.Current.Cache(“mykey”))

End Sub

Advantages to your web application by using ASP.NET Data Caching :

With ASP.Net Caching, you have to add just few line of code will reduce database access from your application.

As web server will send fewer requests to database Performance of web application will be improved. (As in many cases redundant data will be retrieved from ASP.NET Cache)

Quick responding web application, gives more satisfaction to end user, while spending time on your site.

Advertisements