|Lesson 5||Application variables and the race condition|
|Objective||Explain how application variables may be incorrectly updated.|
Application Variables and the Race Condition
Although it can be useful to have a single variable shared among all the users of an application, multiple users sharing the same variable can also produce problems.
For example, incrementing a variable value is a three-step process:
- Get the current value of the counter.
- Add 1 to the current value.
- Store the updated value back in the counter variable.
Suppose two users arrive at our Web site at the same time, and we wish to update the total number of users to include both of our site's latest visitors.
One possible sequence of updates leading to an incorrect value is illustrated in this SlideShow.
- Our website is using an application variable to track the current number of users accessing the site at any time.
- New user Alice arrives at the site, and a new session is created for her.
- However, before the procedure can update the counter variable, user Betty arrives at the site.
- Alice's Session_OnStart procedure completes itself by adding 1 to the value copied from the variable (5), and stores the sum (5+1 = 6) back into the Application variable
- Then Betty's Session_OnStart procedure completes itself by adding 1 to the value copied from the variable
- We started with 5 users and added 2 more users, but our NumCurrUsers variable is showing a total of 6 users.
ASP.NET Core 3
Timing Problem with Shared Application Variable
The race condition
The situation in which multiple users are trying to update the same variable is called a race condition, because the outcome depends on who gets to the variable first.
The solution to the race condition is to make sure that only one person can change a shared variable at any time. ASP contains a way to access Application variables that ensures this: the
When you call the
Lock() method in a script, only that script can modify the Application object. A script using the
Unlock() methods could look likethis:
Application("NumCurrUsers") + 1
Lock() method, Alice, the user from the earlier Slide Show scenario who arrived at our site first would be the only user updating the
NumCurrUsers variable upon opening the application;
Betty would not begin her updating procedure until Alice was done. This time, Betty will retrieve the correct value of 6 and increment it to 7.
You don't have to specifically call
Unlock(), because the server unlocks the Application object when the .asp script file ends or times out.
However, it is good practice to unlock the object as soon as possible, because other users wanting to access the application and update a locked variable will have to wait until the process is complete.
The next lesson describes the object used to read and write text files with ASP.