Introduction
Application variables were under-used on my
site but not for long! I realized recently that a list box that I was populating
with data from my database changed very rarely. Application state is a data
repository available to all classes in an ASP.NET application. Application state
is stored in memory on the server and is faster than storing and retrieving
information in a database. Unlike session state, which is specific to a single
user session, application state applies to all users and sessions. Therefore,
application state is a useful place to store small amounts of often-used data
that does not change from one user to another.
Application state is stored in an instance of
the HttpApplicationState class. This class exposes a key-value dictionary of
objects. The HttpApplicationState instance is created the first time a user
accesses any URL resource in an application. The HttpApplicationState class is
most often accessed through the Application property of the HttpContext class.
Alternatively, you can add objects to the StaticObjects collection via an
<object runat="server"> declaration in your Web application's Global.asax file.
Application state defined in this way can then be accessed from code anywhere in
your application.
Application State Considerations
- Resources : Because
it is stored in memory, application state is very fast compared to saving
data to disk or a database. However, storing large blocks of data in
application state can fill up server memory, causing the server to page
memory to disk. As an alternative to using application state, you can use
the ASP.NET cache mechanism for storing large amounts of application data.
- Volatility : Because
application state is stored in server memory, it is lost whenever the
application is stopped or restarted. For example, if the Web.config file is
changed, the application is restarted and all application state is lost
unless application state values have been written to a non-volatile storage
medium such as a database.
- Scalability : Application
state is not shared among multiple servers serving the same application, as
in a Web farm, or among multiple worker processes serving the same
application on the same server, as in a Web garden. Your application
therefore cannot rely on application state containing the same data for
application state across different servers or processes.
- Concurrency : Application
state is free-threaded, which means that application state data can be
accessed simultaneously by many threads. Therefore, it is important to
ensure that when you update application state data, you do so in a
thread-safe manner by including built-in synchronization support.
Store and Retrieve Application Variables
<script
language="vbscript"
runat="server">
Sub Application_OnStart
application("vartime")=""
application("users")=1
End Sub
</script>