Public classStaticcachetest {Private Staticidictionary<string,Object>_dic; Private Static ObjectLocker =New Object(); Private Staticidictionary<string,Object>Cacheddic {Get { if(_dic = =NULL) { Lock(locker) {if(_dic = =NULL) {_dic=Newdictionary<string,Object>(); } } } return_dic; } } Public Static ObjectGetObject (stringkey) { returnCacheddic[key]; } Public Static voidSetObject (stringKeyObjectobj) { Lock(Locker) {Cacheddic[key]=obj; } } } Public Partial class_default:system.web.ui.page {Private Const stringKEY ="currenttime"; protected voidPage_Load (Objectsender, 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)//is essentially the way Httpruntime.cache is implemented.{staticcachetest.setobject (KEY, curtime); } if(Httpruntime.cache[key] = =NULL) {HttpRuntime.Cache.Insert (KEY, curtime); //Httpruntime.cache is the same object as HttpContext.Current.Cache, it is recommended to use Httpruntime.cache} TextBox1.Text=Httpcontext.current.application[key]. ToString (); TextBox2.Text=Httpcontext.current.cache[key]. ToString (); TextBox3.Text=Staticcachetest.getobject (KEY). ToString (); } }
- HttpContext.Current.Application: The entire application can be shared, of course, when the storage should be locked.
- Httpruntime.cache and HttpContext.Current.Cache: The two are in fact the same object, the difference lies in the implementation of HttpContext and HttpRuntime. HttpContext must be used in the context of ASP. HttpRuntime can be used in any context, for example, httpruntime can be used as a cache in a console program.
- Static variables: Essentially the same as the Httpruntime.cache implementation principle (the cache is also a static variable).
The 1th and 3rd are only suitable for storing small amounts of data (less than 1M), otherwise there will be a loss in performance. Httpruntime.cache is enhanced in terms of efficiency and functionality (such as cache dependencies, expiration policies, etc.), so it should be used as much as possible in real-world applications.
Several ways to globally cache in ASP.