Public Class Staticcachetest
{
Private Static Idictionary <
String ,
Object > _ DIC;
Private Static Object Locker =
New Object ();
Private Static Idictionary <
String ,
Object > Cacheddic
{
Get
{
If (_ DIC =
Null )
{
Lock (Locker)
{
If (_ DIC =
Null )
{
_ DIC =
New Dictionary <
String ,
Object > ();
}
}
}
Return_ DIC;
}
}
Public static Object GetObject ( string key)
{< br> return cacheddic [Key];
}
Public static void setobject ( string key, Object OBJ)
{< br> lock (locker)
{< br> cacheddic [Key] = OBJ;
}< BR >}
Public Partial Class_ Default: system. Web. UI. Page
{
Private Const StringKey ="Currenttime";
Protected Void Page_load ( Object Sender, eventargs E)
{
String curtime = system. datetime. Now. tostring ();
If (Httpcontext. Current. application [Key] = Null )
{Httpcontext. Current. application. Lock ();
Httpcontext. Current. application [Key] = curtime;
Httpcontext. Current. application. Unlock ();
}
If (Httpcontext. Current. cache [Key] = Null )
{
Httpcontext. Current. cache. insert (Key, curtime );
}
If (Staticcachetest. GetObject (key) = Null ) // Essentially, it is the implementation method of httpruntime. cache.
{
Staticcachetest. setobject (Key, curtime );
}
If (Httpruntime. cache [Key] = Null )
{
Httpruntime. cache. insert (Key, curtime ); // Httpruntime. cache and httpcontext. Current. cache are the same object. We recommend that you use httpruntime. Cache
}
Textbox1.text = httpcontext. Current. application [Key]. tostring ();
Textbox2.text = httpcontext. Current. cache [Key]. tostring ();
Textbox3.text = staticcachetest. GetObject (key). tostring ();
}
}
I haven't engaged in Asp.net for more than two years, and I can't even figure out the mechanism for storing some things globally. Today I made a test and verification, and made a record for my reference. The record is as follows:
- Httpcontext. Current. Application: entire applicationProgramCan be shared, of course, the storage should be locked.
- Httpruntime. cache and httpcontext. Current. cache: they actually point to the same object. The difference lies in the implementation of httpcontext and httpruntime. Httpcontext must be used in the context of Asp.net, while httpruntime can be used in any context. For example, httpruntime can be used as the cache in the console program.
- Static variables: essentially, the implementation principle of httpruntime. cache is the same (cache is also a static variable ).
1st and 3rd are suitable for storing only a small amount of data (less than 1 m), otherwise there will be performance loss. Httpruntime. cache improves the memory usage efficiency and functions (such as cache dependencies and expiration policies), so it should be used in practical applications as much as possible.