Multiple session updating the application variable at same time

Hi,

Many a times we want to keep some values in our application, which should be available Application Wide. We normally keep these values in the application variables. This is very handy and fast to use.

One of the examples of use of Application Variable that I normally use is a Boolean value describing if the application is running locally or Live (Production). The value is retrieved in the Application_start event from the web.config file. This is very handy as at many point in the application I keep a check on the work to be done based on this value. And I do not have to refer to the config file all the time to know if the application is running locally or on production.

Writing and reading to an application variable is very simple. We can write to an application variable like this.
Application["Local"] = false;

and to read a value from application variable we can use the following code.

bool blnLocal = Convert.ToBoolean(Application["Local"]);

But what if the value of the application variable changes on every request. Lets say, I want to update (keep) the number of hits in an Application variable. I will have to update the value on every request. But I we have many hits at the same time than this can cause problem as multiple thread will try to update a single value at the same time.

What I can do here is lock the application while we are writing to the Application. This can be done in the following way.

Application.Lock();

Application["requestCount"] = Convert.ToInt32(["requestCount"]) + 1;

Application.UnLock();

what we are doing here is Locking the application while we are updating the requestCount Variable and after we have updated the variable we unlock the application. This way no to thread will be updating the value at the same time.

Vikram

Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2009 Vikram Lakhotia