Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Cache, Session, and ViewState

0.00/5 (No votes)
21 Jul 2008 1  
Properly using cache, session, and viewstate objects in your asp.net application

Download SampleCacheSessionViewState.zip - 5.08 KB

Understanding the differences between Cache, Session and ViewState

This article is originally from http://www.progtalk.com/ViewArticle.aspx?ArticleID=62.

This article will discuss the different types of storage methods, and which may be best for your site. As the number of web applications and developers are growing, there seems to be misunderstandings regarding what method storage method should be used, and when. There are heavy consequences which can result in loss of customers, and viewers based on incorrect strategies being used for development. Let us start, by first examining the different methods.

Understanding Cache

The Cache can be thought of as the memory. It is simply, the memory of the machine/server from which the source code is running from. This is an extremely important feature which can allow you to store difficult and complex constructed data which can be reused.

Imaging you had to query a large set of different databases, which may consist records from databases ranging from MySQL, MSSQL, to ORACLE which were joined using some VB.NET or C# code. Now if the records where changing insignificantly every couple of hours, why would we need to do a live fetch/lookup every time the user wanted to get some information? It would first be slow, and resource intensive as we would have to reconstruct all the data before displaying it to the user. By using Cache, we can store it in memory, and directly bind the data. This would be a more elegant and efficient way to retrieve data, while maintaining optimal performance.

The Cache object can also have an expiration which would allow us to reinstitute data into the memory in intervals. Using the same example as above, we can make the cache expire every two hours, and repopulate the data. It would do this every 2 hours throughout the day, allowing the most up to date data to be fetched. Below is an example of how something can be put into the cache:

//Referenced from msdn http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx

public void AddItemToCache(Object sender, EventArgs e) 
{ 
    itemRemoved = false; 
    onRemove = new CacheItemRemovedCallback(this.RemovedCallback); 
    if (Cache["Key1"] == null) 
        Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60),TimeSpan.Zero, CacheItemPriority.High, onRemove); 
} 


public void RemoveItemFromCache(Object sender, EventArgs e) 
{ 
    if(Cache["Key1"] != null) 
        Cache.Remove("Key1"); 
} 

Understanding Session

A session is defined as a period of time that is shared between the web application and the user. Each user that is using the web application has their own session. Items/Objects can be placed into the Session which would only define these object for that user. Session contains key variables which help to identify the related values. This can be thought of as a hash table. Each user would represent a different key node in the hash identifying unique values. The Session variables will be clear by the application which can clear it, as well as through the timeout property in the web config file. Usually the timeout is 20 minutes by default.

A practical example would be a web application where a user logs into. Each user that logs into your system will have a unique session. We can hold additional data into the session which can be used as the user browses your site. We can hold the first name, last name, and other data simply by adding it to the session:

Session[“FirstName”] = “User First Name”; 
Session[“LastName”] = “User Last Name”; 

//We can clear the session variable by doing the following: 
Session[“FirstName”] = null; 

//We can clear all Session variables by dong the following: 
Session.Abandon(); 
A Session variable should be used with respect to the individual user. It stores the information on the server side and should not be taken advantage of. The difference between the cache and session is that the cache is available to be accessed from the global/application level where one reference to memory is updated. Each request will use the same cache for different users. Session variables will use different session variables for each different user. Usually a large amount of data can be stored on the session, however web sites that have a large amount of traffic usually would not use this method, as it would put a severe load on the server memory.

Understanding ViewState

ViewState is hidden data that is kept by ASP.NET pages. They track the changes to a web site during post backs. All server controls contain a view state. The control will have an EnableViewState property which will allow you to enable/disable if the control properties( e.g. Text, value, etc…) will be held in hidden fields.

The ViewState of a page can be seen if you view the source code of the running page(Right Click --> View Source). It will be listed under the following tags:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value=””></input>

Having a large ViewState will cause a page to download slowly from the users side. When a user clicks on a button and a post back occurs, all the view state information has to be posted back to the server which causes a slower request. Most times this is insignificant, but imagine a person using a dial up connection. If requests, and page loading is taking a couple of minutes, most likely the user will get frustrated, and leave.

ViewState should be limited to what is needed. Most times, a label will not need to have the ViewState enabled as it will not be changing. It can even be directly written using the <span></span> tags in the html eliminating the number of bytes being sent back between post backs.

Data can also be written into the ViewState. The ViewState only persists for the life cycle of the page. If the page redirects to another page, or even to itself, the ViewState will be reset. ViewState should be used to hold small amounts of data, which will be only used on the current page. Below is an example of how we can use the ViewState:

Placing data into a ViewState:

ViewState[“PreviousPage”] = “http://www.google.com”; 

Retrieving data form ViewState:

string PreviousPage = ViewState[“PreviousPage”].ToString(); 

Note: It is good practice to check if an object is null or not first. The above method can be rewritten as the following:

If (ViewState[“PreviousPage”] != null ) 
    string PreviousPage = ViewState[“PreviousPage”].ToString(); 

If you feel I left something out, or stated something which is incorrect, please leave me some comments. I would really appreciate it. Any suggestions will be greatly appreciated.

This article is originally from http://www.progtalk.com/ViewArticle.aspx?ArticleID=62.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here