Hour 5: Understanding 5 ASP.NET State Management Techniques in 5 hours



Application State: stores global objects that can be accessed by any client.

It supports the same types of session state support that are of type objects, retains information on the server, and uses the same dictionary-based syntax. Application state is based on the System.Web.HttpApplicationState class, which is provided in all web pages through the built-in Application object.

Points to remember:

  1. application state items are stored as objects, so you need to cast them when you retrieve them from the collection.
  2. Items in application state never time out.
  3. Application state information is always stored in a process. This means you can use any .NET data types.
     
  4. Application state isn't often used, because it's generally inefficient and its rarely used in practical scenario because its most common uses have been replaced by easier and more efficient methods.
     
  5. We use application state to store database connection strings, which are stored now in a web.config file, which is more flexible.
  6. Previously application state was used to store more frequent data like full product; now you can use an ASP.NET cache, which are more efficient.

Example: We are often interested in knowing how many times a given page has been requested by various clients. Using an application state variable we can do this:

protected void Page_Load(object sender, EventArgs e)
    {
        int count = 0;
        if (Application["HitCounterForOrderPage"] != null)
        count = (int)Application["HitCounterForOrderPage"];
        count++;
        Application["HitCounterForOrderPage"] = count;   
        lblcounter.Text = "Page Visited: " + count.ToString() + "Times";       
    }


Problem with this approach: In the above code, a page counter would probably not keep an accurate count, particularly in times of heavy traffic. For example, if two clients requested the page at the same time, you could have a sequence of events like this
  1. User A retrieves the current count (432).
  2. User B retrieves the current count (432).
  3. User A sets the current count to 433.
  4. User B sets the current count to 433.

To avoid this problem you can use a mechanism to lock and unlock application state:

Application.Lock();
        int count = 0;
        if (Application["HitCounterForOrderPage"] != null)
        count = (int)Application["HitCounterForOrderPage"];
        count++;
        Application["HitCounterForOrderPage"] = count;
Application.UnLock();
lblcounter.Text = "Page Visited: " + count.ToString() + "Times";  

When to use: You are storing infrequently changed, application-scope information that is used by many users, and security is not an issue. Do not store large quantities of information in an application state object.

This is end of your fifth hour of reading. Hope you enjoyed it.

Up Next
    Ebook Download
    View all
    Learn
    View all