Application State In ASP.NET

In this blog you will get the answers to the following questions

  • What is Application State?
  • How does Application State work?
  • What is ASAX file?
  • How do we create Application state key and assign value?
  • Locking / Unlocking Application state.

What is Application state?

Application state is used to maintain the state on the server side. Its state is available through out all the users of the application. It means these state values are maintained on the application level and not on the user level and user session level.

Application state does not have default expiry or you can not set an expiry of the application state.

The dark side of it is that it loses the data, when the things given below occur.

  1. config file get changed / modified.
  2. BIN folder changes / updation.
  3. App_Code folder changes.

For us, above reason is sufficient to understand the dark side of the Application state.

Mostly people use this Application state for the reasons given below.

  1. Counting clicking.
  2. Store common data
  3. To display total online users.
  4. Total orders received. etc…

How does Application state work?

Application state data is available to all the users with the help of HttpApplicationState class. You can create and retrieve the value of the Application state with Key-Value pair dictionary of the objects.

GLOBAL.ASAX file?

This is a global Application class, where we can set the code for the events given below.

EVENT TYPESEVENT DESCRIPTIONS
Application StartThis event is called, when application getting start.
Application EndThis event is called before an Application ends.
Application ErrorThis event is called, when an un-handled error occurs.
Session StartThis event is called, when a new session is starts.
Session EndThis event called, when a session expires.

How to create Application state key and assign value?

To create a new Application, state key is very simple. You can create and retrieve the value of the Application state with Key-Value pair dictionary of the objects.

Syntax

Application[“KEY”] = VALUE;

Example

Application[“ProjectName”] = “Csharp Corner”;

Locking / Unlocking Application State

As you know now, Application state is a center place to store the data or the values for all the users. It is stored on the Application level and not on user level.

To update correct data and values, we need to lock and unlock the value of the Application state variable.

  • Lock()- Lock method is to used to lock the variable to update.
  • UnLock()- Unlock method is used to release variable status of lock.

    Example
    1. //To Lock the application state  
    2. Application.Lock();  
    3. //Update the value of application state  
    4. Application["TotalOnlineUsers"] = ((int) Application["TotalOnlineUsers"]) + 1;  
    5. //To Unlock the application state  
    6. Application.UnLock();