Application object
In the lesson about variables we have seen how
we can use variables inside a page. Unfortunatley those variables aren't available
outside a page and therefore not suitable to share data between pages.
If we want to do that, we have to use the Application
object. This object makes it possible to share data between all the pages in an
(IIS) application.
With the Application object we can for example make a counter
that counts how often a page has been visited, but also save data about the database connection,
or other values that we need throughout the entire site.
We will show what a counter looks like (refresh the page to see the result):
appvar1.asp
<%
Option Explicit
%>
<HTML>
<BODY>
<%
Application("Counter") = Application("Counter") + 1
Response.Write Application("Counter")
%>
</BODY>
</HTML>
Suppose that two different people look at that code at the same time. Because ASP
doesn't finish all of the scripts entirely in one go, but sometimes stops the execution
to (partly) finish another script, it could be possible that the value you see isn't correct.
The value could have been read by the script of user1, and then read by the script of
user2, while user1's script has been stopped temporarily. Now user2's script raises the value
with one, and then shows the value in the browser, after which user1's script does the same.
Because both first read the same value, and then update, the value is only raised by one, instead
of by two. This isn't a big problem with a counter, but it could be that this is important
information. If that's the case you can use the Lock
method to make sure that it won't be possible for other users to get acces to
the values in the Application object at the same time.
Because this works delaying, this should only be done if it's necessary. You should also
use the Unlock method as soon as you're done.
appvar2.asp
<%
Option Explicit
%>
<HTML>
<BODY>
<%
Application.Lock
Application("Counter") = Application("Counter") + 1
Response.Write Application("Counter")
Application.Unlock
%>
</BODY>
</HTML>
The Application object has more possibilities. Because they
aren't used very often, these possibilities aren't part of this lesson.
|