Practical C# 3: Programmatic Caching

Caching is the process of storing frequently used data on the server to fulfill subsequent requests. Grabbing objects from memory is always much faster than re-creating the web pages or items contained in them from scratch each time they are requested.  Caching increases performance, scalability and availability.

 

Another method of caching is to use the Cache Object to start caching specific data items for later use on a particular page.

 

Although Caching is quite similar to the Session state object, the Cache Object is shared by all users of the particular web server’s app domain that is hosting the application. So if you put a particular item in the Cache, all users will be able to see that object.

 

When not to use Caching à Storing user-specific information, I use Sessions instead

 

When to use Caching à ex. Data-tier objects that can be shared by all users.

 

Ex.

 

Typical  Login.aspx.cs

 

Sybase_ARSystem sarCX = new Sybase_ARSystem(CS_List.ConnectionString_CX);
Cache["sarCX"] = sarCX;

 

Sybase_ARSystem” à the non-static util class that performs all calls to Sybase(or any data store) stored procedures. In this case since this will called again and again in making a new request but it doesn’t contain user-specific information, then this is object is a good candidate to cache.

 

 

Then in FooWebFormThatHasADropdownListThat.aspx.cs in populating (for example) the Category Dropdownlist:

 

private void DDL_loadCategory()

    {

        Sybase_ARSystem sarCX;

        if (Cache["sarCX"] == null)

        {

            sarCX = new Sybase_ARSystem(CS_List.ConnectionString_CX);

            Cache["sarCX"] = sarCX;

        }

        else

            sarCX = (Sybase_ARSystem)Cache["sarCX"];

 

        DataTable categoryList = sarCX.CATEGORY_SELECT();

        ddlCategory.DataTextField = "CATEGORY_NAME";

        ddlCategory.DataValueField = "CATEGORY_ID";

        ddlCategory.DataSource = categoryList;

        ddlCategory.DataBind();

 

         

    }

 

CASE IN POINT #1: Always perform checks if the cache object is still available.

Cache items only have certain lifespans so be sure to always recreate them.

 

CASE IN POINT #2: Always perform continuous testing for this technique specific to the web application.

 

Published 06-20-2009 9:56 AM by avcajipe
Filed under: , ,

Comments

# re: Practical C# 3: Programmatic Caching

Sunday, June 21, 2009 8:37 PM by cruizer

If you aren't careful, excessive use of caching can actually affect your site's scalability.