"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Saturday, January 26, 2013

Exploring more into caching in asp.net-- Data Caching (Part 4)


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"] = "Arun Aravind";

 The stored string value can be retrieved like this:


if (Cache["name"] != null)
            Label1.Text = Cache["name"].ToString();
 
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.


protected void Page_Load(object sender, EventArgs e)
    {
        ArrayList datestamps;
        if (Cache["datestamps"] == null)
        {
            datestamps = new ArrayList();
            datestamps.Add(DateTime.Now);
            datestamps.Add(DateTime.Now);
            datestamps.Add(DateTime.Now);

            Cache.Add("datestamps", datestamps, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 60), System.Web.Caching.CacheItemPriority.Default, null);
        }
        else
            datestamps = (ArrayList)Cache["datestamps"];

        foreach (DateTime dt in datestamps)
            Response.Write(dt.ToString() + "<br />");
    }


If u had any trouble just ask, Happy to help u :)
Stay Tune...
Have a nice day... 'N happy Coding :)

No comments: