State Management Part 6 - Application State

Name: *
My email: *
Recipient email: *
Message: *
Fields marked as bold are compulsory.
You haven't filled in compulsory values. The email is not correct

Application State is the last part of my state management group of articles. Its use is quite similar to caching so most developers choose to take on that, instead. Thus Application state is not a widely used method. In contrast to other state management tools, it can be found only in Microsoft applications.

What is application state?

Application state is a technique to store data in the server. Consider it like using Session; however there is only one application state. It is created when the application starts and is disposed when it is terminated. So instead of having a different session for each client, all clients share the same application.
 

How the application state works

Application state uses dictionary-like method to store and retrieve information. Using it is quite simple - the same way you would use caching or session instead.
 
To store the value use 
Application[key] = value; 
 
To retrieve a value use
value = Application[key];
 
Keep in mind that in order to avoid a NullReferenceException, you should check for null before retrieving the value. Furthermore, to get the actual value you stored you should use casting first. Check out the following piece of code.
 
if (Application[key] != null)
            var = (classToCast)Application[key];
 
 

Example

We are going to create a page containing a button. Each time the button is pressed, a counter stored in the application will increase by one. Furthermore, the time it was pressed will be stored in the application state as well.
 
The ApplicationState.aspx page contains a button and a label. That label will tell us how many times the button has been clicked and the last time clicked.
 
 
 
    <asp:Button runat="server" ID="CounterButton" OnClick="CounterButtonClicked" Text="Click To Increase Counter" />
    <br />
    <asp:Label runat="server" ID="CounterLblID" />
 
 
The code behind file contains the following piece of code, executed when the button is clicked.
 
 
    protected void CounterButtonClicked(object sender, EventArgs e)
    {
        //Initialize variables
        int clickCounter = 0;
        DateTime lastClick = DateTime.Now;
 
        //Get counter from application state
        if (Application["ClickCounter"] != null)
            clickCounter = (int)Application["ClickCounter"];
 
        clickCounter++;
 
        //Store values in application state
        Application["ClickCounter"] = clickCounter;
        Application["LastClick"] = DateTime.Now;
 
 
        //Create the label text
        string labelText = "This button has been clicked " + clickCounter.ToString() + " times.";
        if (lastClick != DateTime.MinValue)
            labelText += "LastClick  at : " + lastClick.ToString("HH:mm:ss");
 
 
        CounterLblID.Text = labelText;
    }
 
 
 
Since application state is common to all clients, the first time a user, John for instance, clicks the button the result will be "This button has been clicked 1 times". When the next user, Mary, clicks the button the result will be "This button has been clicked 2 times". Application state is just the same for all users.
 
However, what would happen in case John and Mary clicked their button at exactly the same time. They would both get the value 2 and would both increase it on their own. So the result would be "This button has been clicked 3 times", yet, you can tell this is wrong. Application state offers a solution. You can use Application.Lock() and Application.UnLock() to deny other users from editing application state in between these methods. This is what the previous example would look like if we had used Lock and UnLock.
 
 
    protected void CounterButtonClicked(object sender, EventArgs e)
    {
        //Initialize variables
        int clickCounter = 0;
        DateTime lastClick = DateTime.Now;
 
        //Lock the application state
        Application.Lock();
 
        //Get counter from application state
        if (Application["ClickCounter"] != null)
            clickCounter = (int)Application["ClickCounter"];
 
        clickCounter++;
 
        //Store values in application state
        Application["ClickCounter"] = clickCounter;
        Application["LastClick"] = DateTime.Now;
 
        //Unock the application state
        Application.UnLock();
 
        //Create the label text
        string labelText = "This button has been clicked " + clickCounter.ToString() + " times.";
        if (lastClick != DateTime.MinValue)
            labelText += "LastClick  at : " + lastClick.ToString("HH:mm:ss");
 
 
        CounterLblID.Text = labelText;
    }
 
Using these methods, supposing John was the first user to access the application state, Mary would have to wait for him to unlock the application, before she could get to use it. If, for some reason, it took John 30 seconds to unlock the application Mary would have to wait a long time before she could get her response. This is no good either, so we should be careful when to use Lock and UnLock. Keep in mind that caching has its own similar locking methods.
 

More about application state.

Application state is stored in the server so there is no way that someone can steal away information. 
 
You can store any type of information you want within application. Just make sure you cast the value before you use it.
 
Values stored in application state never time out. So you should keep in mind not to store large amount info or you may slow down the server.
 
So, you may ask, since caching and application state have so much in common, when is the best time to use one each of them? In fact most ASP.NET developers tend to use cache alone, since it is more delicate and offers much more options than application state. On the other hand, even using priority parameters in caching, there may still be a time when your value can be removed due to extreme memory usage. Application state holds no such danger. Yet it is not much used and exists primary to achieve backward compatibility with asp. However a developer could still use both cache and application state at the same project to avoid response time increment due to cache locking issues- even if you have locked cache, you can still use application state.
 

Conclusion

Application state is a way to store values in the server. Each value is shared by all users and will remain in memory till the application is terminated. Many developers regard it as old time technique and avoid it, choosing caching instead, but there are still those who insist on using it.
 

Back to BlogPreviousNext

Comments


  • 16-07-2015, 21:06 PM
    Serizawa
    Posts: 1
    I wasn't aware of some of the material that you wrote about so I want to just say thank you for potinsg, i am just a newbie in the internet business, need to learn a lot from the gurus.

Leave a comment
Name: