Application Object in Asp.net

The Application object holds information that will be used by many pages in the application with many users. The information can be accessed from any page. The changes will automatically be reflected on all pages.If data needs to be shared between different clients, then application state can be used. Application state can be used in similar to the way session state is used.

In the following example, the application variable with the name userCount is initialized when the Web application is started. Application_Start() is the event handler method in the file global.asax that is invoked when the first ASP.NET page of the website is started. This variable is used to count every user accessing the website:
 
void Application_Start(Object sender, EventArgs e)
{   
    // Code that runs on application startup
    Application["userCount"] = 0;
}
 
In the Session_Start() event handler, the value of the application variable userCount is incremented.To avoid Deadlock we can use Lock & Unlock properties.
void Session_Start(Object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Application.Lock();
        Application["userCount"] = (int)Application["userCount"] + 1;
        Application.UnLock();
    }


No comments:

Post a Comment