Working with Application State

When developing web applications, it is often necessary to maintain information that is applicable to the entire site. Site-wide information is often stored in databases, but can also be stored in application state within ASP.NET. If the information you need to store is small, but will be accessed quite often, then using application state will be faster and more memory-efficient than continually reading and writing site-wide data to and from a database.

Application state is accomplished through the storage of name/value pairs in an instance of the HttpApplicationState class. Every page in an ASP.NET application has access to this instance in the page's Application property. The HttpApplicationState class operates just like any other dictionary, where you can set and retrieve values using numeric or string indexes:

Application["myValue"] = 21; Application.Add("anotherValue") = "Hello"; foreach (string key in Application.AllKeys) {     Response.Write(Application[key]); } 

Because application state is stored in such a wide scope, you can potentially have hundreds or even thousands of page requests attempting to write to the same state variable at the same time. As you saw in Chapter 10, "Multithreaded Programming," data can quickly become corrupted when accessed by multiple threads at the same time without proper protection. You can protect code that writes to an application state variable from simultaneous writes by using the Application.Lock() and Application.UnLock() methods. These methods are essentially wrappers around the C# lock keyword, using the application state object as the lock source, as shown in the following example:

Application.Lock(); Application["myVariable"] = 121; Application.UnLock(); 

With the preceding lines of code, you can guarantee that only one request will write to application state at any given time.


Be careful when you use the Application.Lock() and Application.UnLock() methods. If you accidentally lock the application without unlocking it, you could wind up causing a large slowdown or even page failure. You might want to consider using a code snippet for application state access that automatically includes a corresponding UnLock() method for the Lock() method, guaranteeing that you will always unlock the application state object when you're done writing the state variable. Make sure that you unlock the application state as soon as possible to avoid keeping other pages waiting for state data.

If you add a "Global Application Class" file to your project, you will add the Global.asax file. This file contains several events that can be used to initialize state. One such event is the Application_Start event, which can be used to initialize application state variables, as shown in the following code:

void Application_Start(object sender, EventArgs e) {     // Code that runs on application startup     Application["counter"] = 0; } 

Listing 23.1 shows the ASPX and C# code for a page that displays the current value of an application-wide counter variable as well as prompting the user to click a button to increment the counter.

Listing 23.1. Using Application State

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form  runat="server"> <div> <asp:Label  runat="server" /><br /><br /> Press the "Increment Counter" button to increase the application-wide counter<br /> <asp:Button  runat="server" OnClick="btnIncrement_Click" Text="Increment Counter" /><br /> </div> </form> </body> </html> Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {     UpdateCounterLabel(); } protected void btnIncrement_Click(object sender, EventArgs e) {     Application["counter"] = (int)Application["counter"] + 1;     UpdateCounterLabel(); } private void UpdateCounterLabel() {     lblAppCounter.Text = string.Format(       "Current value of application-wide counter is <b>{0}</b>.<br/>",         Application["counter"]); } } 

As mentioned earlier, you want to use application state to store small amounts of frequently accessed information. The larger the data you store in the application state, the higher the risk of having application state objects slow down your application. Larger amounts of less frequently accessed data would be more efficiently stored in a database or in an application configuration file.

Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298 © 2008-2017.
If you may any questions please contact us: