Setting Global Objects in Global.asax
From a forum request :)
ASP.NET includes a Global.asax file which exposes many application-wide events which you can use to control your application execution.
It also allows you to define globally-scoped objects. However, a word of caution…as each page in an ASP.NET page runs in its own thread, you need to make sure your objects are thread safe for multiple users requesting your site.
Why is this important? Imagine 2 requests, from user A and user B. Each request runs in a separate thread, and user A manipulates a global object in one thread, and user B manipulates the same object in a different thread. Depending on Windows, these might be executed in any order…meaning your global object won’t be synchronized for both users.
So to avoid this complication, use thread-safe objects, or, of particular interest, use a hashtable as a thread-safe container for your variables:
using System;
using System.Collections;
namespace MyApp.Collections {
public class globalVariableStore{
private Hashtable myCollection;
private Hashtable threadSafeCollection;
public globalVariableStore()
{
myCollection = new Hashtable();
threadSafeCollection = Hashtable.Synchronized(myCollection);
}
public void addVariable(string name, object value)
{
threadSafeCollection[name] = value;
}
public object retrieveVariable(string name) {
return threadSafeCollection[name];
}
}
}
You can then define an instance of your globalVariableStore as globally-scoped by adding a line to your global.asax file: