JavaScript EditorJavascript debugger     Javascript examples

Team LiB
Previous Section Next Section

Using Application State

Application state refers to any data that you want to share among multiple users of your application. This can include connection string information for databases (although this information is often better to limit to the business tier of an application), shared variables, and cached datasets (although these might be better stored using the ASP.NET cache engine, which is discussed in more detail in Chapter 12). In fact, one of the difficulties of managing application state is choosing from the many available options for storing such state.

Like classic ASP, ASP.NET provides a collection of key-value pairs that developers can use to store values and object instances. This collection can be accessed as shown in the following code example:

Application["MyApplicationVar"] = "MyValue" MyLocalVar = Application["MyApplicationVar"];

Application state storage in ASP.NET is supplied by the .NET HttpApplicationState class (which resides in the System.Web namespace), an instance of which is exposed as the Application property of the Page class. Because every ASP.NET page inherits from the Page class, you can access the Application property as if it were an inherent property of the page, as shown in the preceding code.

For backward-compatibility with classic ASP, the ASP.NET Application object exposes a Contents property that can be used to access individual values, using the appropriate key.

Application.Contents["MyApplicationVar"] = "MyValue" MyLocalVar = Application.Contents["MyApplicationVar"];

New in ASP.NET is the ability to add items to the HttpApplicationState collection using the Add method exposed by the Application object. You can use the Remove method to remove items from the Application collection. (In classic ASP, the Add and Remove methods are exposed by the Application.Contents collection.)

Application.Add("MyApplicationVar", "MyValue") Application.Add("MyOtherApplicationVar", "MyOtherValue") Application.Remove("MyOtherApplicationVar");

You can also clear the contents of the Application collection by using the Clear method exposed by the Application object (or the RemoveAll method, which is provided for backward-compatibility with classic ASP).

//Either line below will clear the application stat Application.Clear() Application.RemoveAll();

The Application object exposes several other ways to access and modify the values stored in the Application collection, as shown in Table 4-1.

Table 4-1: Application Object Methods and Properties

Method or Property


AllKeys property

Returns a collection of all of the keys by which Application collection values can be accessed.

Count property

Returns the number of objects stored in the Application collection.

Get method

Returns an item from the Application collection by key or by index.

Set method

Updates an item in the Application collection by key or by index.

GetKey method

Returns the key for an item based on a supplied index.

ToString method

Returns a string that represents an item in the Application collection. Useful when a string value is required, rather than an object reference.

In addition to storing values in the Application collection, you can instantiate and store references to .NET components, such as DataSets, in application state using the <object runat="server"> tag syntax in the Global.asax file (or its associated code-behind file). These objects then become part of the Application object’s StaticObjects collection and can be referenced in your ASP.NET Web Form pages by referring to the id attribute associated with the object.

// Global.asa <object runat="server" id="MyClassInstance" class="MyClassName"     scope="Application"> </object> // Web Forms pag Response.Write("Value = " + MyClassInstance.MyValue);

Global.asax (or its associated code-behind file) is the only mechanism for creating object instances with Application scope.


When you’re using either the Application or Session collections, it’s a good idea to initialize the variables you’re using to a default value (such as "" for a string or 0 for a numeric) in the Application_Start or Session_Start event handlers in Global.asax. You can then test for the default value as a way of determining whether it has been altered.

Synchronizing Access to Application State

One challenge in managing state information that’s shared between multiple users is ensuring that no two users can attempt to update the state information simultaneously, which could lead to corruption of the data being stored. Like classic ASP, the ASP.NET Application object provides Lock and UnLock methods that developers can use to ensure that only a single user can update application state information at any given time. Developers should call Application.Lock() prior to modifying any data stored in the Application collection, and call Application.UnLock() once the modification is complete. Keep in mind that while the application is locked, no other users can modify data stored in the Application collection, which can cause scalability problems. For this reason, you should make sure to keep the application locked for the shortest time possible, and perform as little work as possible while the application is locked.

Reading and writing application state is easy. The output for this example will be written into an ASP.NET Label server control.

Read and write application state

  1. Open Visual Studio .NET and create a new Web Application project called Chapter_04.

  2. Place your mouse pointer over the Toolbox on the left side of the screen. When the Toolbox appears, select a label and drag it onto the screen.

  3. With the label control selected, change the ID of the label from Label1 to Message. The screen should look something like the following illustration.

    Click To expand
  4. From the View menu, select Code, or press F7 to open the code editor.

  5. Locate the Page_Load method, and add the following code:

    //Initialize looping variabl int loopCount = 0 //Lock the application object before we manipulate i Application.Lock() Application["TestString"] = "Hello" Application.Add("TestNumber", 43) //Now unlock the Application, since we will no //just read from the Application object Application.UnLock() Message.Text = "There are " + Application.Count.ToString() +                 " items in the Application collection.<br/>" while (loopCount < Application.Count     Message.Text += "Application(" + loopCount.ToString()                     ") = " + Application[loopCount] + "<br/>"    loopCount += 1 }
  6. Save the page and its code-behind module by selecting File, then Save All (or by pressing Ctrl+Shift+S).

  7. Select Build Chapter_04 from the Build menu to build the application.

  8. Test the page by right-clicking WebForm1.aspx in Solution Explorer, and then selecting View In Browser. The resulting screen should look similar to the following illustration.

    Click To expand

Recommendations for Application State

Information stored in application state can be easily shared among all users of an application. This can make it very tempting to use application state to store all manner of data, from application settings such as database connection strings to cached datasets containing frequently used data. In many cases, there are more efficient means of storing this data than application state. Table 4-2 shows some examples of when you might or might not want to store information in application state, as well as alternatives for storing such information.

Table 4-2: Application State Recommendations

State Information



Database connection strings or other application configuration settings

Typically, these settings are accessed infrequently. Storing this information in application state is not very efficient.

Use the Web.config configuration file to store this information, and retrieve with the AppSettings property of the ConfigurationSettings Class, as discussed in Appendix B.

Datasets containing frequently read data

Caching frequently used data at the application level can be efficient, but there’s little automatic control over when the data is refreshed.

Use the ASP.NET cache engine to cache expensive or frequently read data. The ASP.NET cache engine provides fine-grained control over how and when data is refreshed or purged from the cache. (See Chapter 12 for more information.)

Shared application flags or counter variables

Shared values that can be updated by multiple users of an application can present major scalability issues, as discussed in “State and Scalability” later in this chapter.

Consider storing shared application flags in a database, which will provide finer- grained control over the reading and updating of individual values.

References to object instances

Storing references to objects with the wrong threading model (such as legacy COM components created with Visual Basic) can have a severe impact on the scalability of an application.

If it’s absolutely necessary to store a reference to an object instance, ensure that the class from which the object is created is thread safe.

Limitations of Application State

Application state has several limitations that you should consider when deciding how to manage your state information.

  • Durability Application state lasts only as long as the Web application is running. If the Web application or Web server is shut down or crashes, any state information stored at the application level will be destroyed. Any information that needs to persist between application restarts should be stored in a database or other persistent storage.

  • Web farms Application state is not shared across multiple servers in a Web farm (nor across multiple processors in a Web garden). If you need to store values that must be available to all users in these scenarios, application state is not an appropriate choice.

  • Memory Any given server has only a limited amount of physical memory available. Overuse of application state can result in information being swapped to virtual memory (a location on a hard drive used to provide supplemental “memory” storage). This can reduce performance significantly.


Web farms are groups of identically configured servers that share the load of serving user requests for a given Web application. Each server contains the same content and can fulfill any request. Requests are routed to individual servers by a hardware- or software-based load-balancing algorithm that either determines which server is least loaded or assigns requests to a given server randomly.

Web gardens are a new concept in ASP.NET in which an application can be set to run on specific processors on a multiprocessor server.

Team LiB
Previous Section Next Section

JavaScript EditorJavascript debugger     Javascript examples