ASP.NET Server Side State Management – Application State
In this post I’ll introduce the application state technique as the first
ASP.NET server side state management techniques.
You can read my previous posts in the state management subject in
the following links:
- Client side state management introduction
- ViewState technique
- Hidden fields technique
- Query strings technique
- Cookies technique
- Control state technique
- ASP.NET server side state management
What is application state?
Application state is a global storage mechanism that saves data
that can be accessed from every web page in a web application.
The data that is saved in the Application is maintained between
every request that is sent to the server. The application state is
maintained in the HttpApplicationState class which is implemented
as a dictionary. The Application is a good place to hold data which
is global for the web application and isn’t connected to a specific user.
By placing the data in the application state you gain a single access point
for shared application data. The data that you save in the application state
isn’t permanent and is cleaned whenever the application restarts.
There are three main events in the application state life cycle which
can be customized. The events are:
The events occur as indicated by their names – at the application start, at the
application end and when an unhandled error is raised in the application.
The events can be implement in the Global.asax file:
How to Use Application State Data?
As written earlier the application state storage is an
instance of the HttpApplicationState class. The HttpApplicationState
class is implemented as a dictionary and therefore the use of it is simple.
The only problem with the Application is that it can be updated from
multiple web pages. Therefore, you have to lock the Application object
before you make any update to data that it holds.
An example of how to update an Application variable:
In the example you can see that I concat a string to a stored variable.
Before doing the operation I use the Lock method of the Application
object to lock the object. After the operation I use the UnLock method
of the Application object. You don’t have to lock the Application when
initializing variables in the Application_Start event.
Remember to use locking whenever you update a record or else if the record
can be updated from another page the web application can become inconsistent.
The example above showed how to read a value (which need to be cast)
and how to write a value to the Application storage.
To sum up the post, the application state enable us to store global
data for our application. Even though, I prefer to use that storage with
caution because if it is over used it can have a major impact on the
memory usage of the application. The next stop in this series will be the
session state technique.