Here is the example of doing the same. i took it from Mr Brij's article so if it helps do vote that article too(link is below)
A classic example of Application variable can be to show the number of online user in a website. This can be done in the following steps:
Add an online counter variable ApplicationStart method of Global.asax file as:
Application["OnlineCounter"] = 0;
So in this, a variable will be added when the application first starts and will be initialized to 0 as there will be no logged in user at that point of time.
Now as we know whenever a new user opens the website, a new session is created and Session_Start method of Global.asax is called. So we can increase the counter in this method as:
void Session_Start(object sender, EventArgs e)
{
if (Application["OnlineCounter"] != null)
{
Application.Lock();
Application["OnlineCounter"] =
((int)Application["OnlineCounter"]) + 1;
Application.UnLock();
}
}
We should use the Locks, else we may get the wrong result because this may be updated at the same time and updated data is not correct. How: Let's say we currently have Application["OnlineCounter"] is 5 and at the same time, two sessions read the value 5 and make an increment to 6 and updated it. Application state as 6. So although two users are logged in, the counter is increased by one only. So to avoid this, we should use the locks.
So also at the time session ends, we should decrease it by one. As I already discussed, an event Session_End is fired whenever a session ends. So it can be done as:
void Session_End(object sender, EventArgs e)
{
if (Application["OnlineCounter"] != null)
{
Application.Lock();
Application["OnlineCounter"] =
((int)Application["OnlineCounter"]) - 1;
Application.UnLock();
}
}
And this value can be accessed throughout the application at any point of time in the application as:
if (Application["OnlineCounter"] != null)
{
int OnlineUsers = ((int)Application["OnlineCounter"]);
}
and this value can be used anywhere in the application.
P.S. link of the article:
A Walkthrough to Application State[
^]