Using Application and Session Variables

Application and session variables work similarly, with each having a dictionary of objects. Keys (which must be strings) identify each object in the dictionary. The keys are normal text strings that give a name to each object in the dictionary. For example, I might have a user ID object and I name it UserID. The following simple example shows how an integer value of 12 can be stored in a session variable named UserID:

C#
 Session["UserId"] = 12; 
VB
 Session("UserId") = 12 

It is just as easy to set a session variable to contain a string. The following examples show how to set session variables in C# and VB to a string containing the name John Doe:

C#
 Session["UserName"] = "John Doe"; 
VB
 Session("UserName") = "John Doe" 

Session variables can also contain any sort of object that you want to store. To store an object in a session variable, you simply figure out what key name you want to give a session variable, and then assign that name to the object. The following examples show how to assign an object into a session variable in C# and in VB:

C#
 Session["SomeGreatObject"] = MyObject; 
VB
 Session("SomeGreatObject") = MyObject 

To create and assign values to an application variable, you do exactly the same thing. Application variables, though, usually apply to the entire application and are thus more global in nature. One of the more common application variables people use is for traffic counters. The following examples show how to increment a counter in C# and in VB. Note that the customary unary increment operator is not available in C# as you might expect it to be on application and session variables. That is because in C# language, the application variable is seen as an object rather than a value type. The example includes two notes you should pay heed to.

C#
 Application["Counter"] = (int)Application["Counter"] + 1; 

Note that the following code will generate the error: No such operator '++' defined for type 'object'

 Application["Counter"]++; 

Note also that the following code will generate the error: Operator '+' cannot be applied to operands of type 'object' and 'int'

 Application["Counter"] = Application["Counter"] + 1; 
VB
 Application("Counter") = Application("Counter") + 1 

It is sometimes important to check the variable to see whether it exists. Many times, the application or the session hasn't created a variable yet, and you can't access a variable until it has been created. Until a variable has been created, it doesn't exist and the program throws an exception when you try to access such a variable. In C#, you check to see whether a variable is equal to null, and in VB you check to see whether it is equal to Nothing (with a statement such as my OBJ==null or OBJ=Nothing). The following code shows how to check session and application variables in both C# and VB to see whether they exist or have not yet been created:

C#
 // Check an application variable for null if( Application["SomeKey"] == null ) {     // Do something here to initialize the variable } // Check a session variable for null if( Session["SomeKey"] == null ) {     // Do something here to initialize the variable } 
VB
 ' Check an application variable for null If Application("SomeKey") = Nothing Then     ' Do something here to initialize the variable End If ' Check a session variable for null If Session("SomeKey") = Nothing Then     ' Do something here to initialize the variable End If 

Application variables are really global variables for an entire ASP.NET application. These variables are available for every user who is currently accessing the application except those who are accessing the application across a Web farm. You should always carefully consider the impact of storing anything as a global variable. Keep the following in mind:

  • Resources that application variables consume

  • Concurrency and synchronization

  • Scalability implications of using application variables

  • Life cycle implications of using application variables

You also want to keep session data to a minimum, if possible especially when a site is a high-traffic site. Session variables as implemented by default take up system memory resources for as long as a session is active. If your site gets hit from 10,000 unique users in a minute, for example, and your session lasts for 20 minutes, you could be storing session data for 200,000 users. If the data stored were 100 bytes, your session would use 20MB of your system memory. If the data stored were 1000 bytes, the session data would be 200MB. As you can see, this use of system resources can easily get out of hand.

Resources That Application Variables Consume

The memory occupied by a variable stored within application variables isn't released until the value is either removed or replaced. Keeping items in application variables that are not used very often is not a good idea. For example, if you store a recordset that is 10MB or so, and you don't use it very often, this storage is an expensive use of these resources.

Concurrency and Synchronization

Multiple running threads within an application cannot simultaneously access values stored within application variables. This means that you must be careful about accessing these variables. You must ensure that an object stored in an application object is free threaded (able to be accessed from multiple threads) and contains built-in synchronization support. If you don't do that, and an object in an application is not free threaded, you must provide your own synchronization. To do this, use the Lock() and Unlock() methods.

Scalability Implications of Using Application Variables

You might be forced at times to use locks that protect global resources. Code that runs on multiple threads and accesses these global resources will ultimately end up contending for the resources. This situation causes the operation system to block some threads while others access the resource. A server bearing a heavy load can cause severe thread thrashing (wherein different threads spend inordinate amounts of time waiting for their chance to perform operations) on the system, which can significantly affect the performance of your Web application.

Life Cycle Implications of Using Application Variables

Developers should be aware that .NET applications can be torn down and destroyed at any moment during application execution. This destruction could be the result of crashes, code updates, scheduled process restarts, and other things. Global data stored in application state is not durable; it is lost when the host containing it is destroyed. Developers who want to store a state that survives these types of failures should store either in a database or some sort of other durable storage. (We'll discuss using the Cache API in the section that comes later entitled "Using the Cache Object.")



ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ISBN: 321159659
EAN: N/A
Year: 2003
Pages: 175

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net