Reposted from Jun. net
Someone has already said this topic. Related links:
Httpruntime. cache vs. httpcontext. Current. Cache
Http://weblogs.asp.net/pjohnson/archive/2006/02/06/437559.aspx
Httpcontext. cache and httpruntime. Cache
Http://blog.joycode.com/dotey/archive/2005/01/15/43091.aspx
What I want to talk about here is from another perspective:
I. Two implementationsCodeDifferences:
We use. Net reflector to view the cache attribute of the httpcontext class and see the following code:
Public Cache ... {Get...{ReturnHttpruntime. cache ;}}
Therefore, the two are completely consistent in code.
2. The difference between the two lies in httpcontext. Current
Use. Net reflector to view httpcontext. Current as follows:
Public Static Httpcontext current ... {Get...{Return(Contextbase. CurrentAsHttpcontext );}}
The current static attribute of the contextbase class is as follows:
Internal Static Object Current ... {Get...{ReturnCallcontext. hostcontext ;}}
The Static Property hostcontext of the callcontext class is as follows:
Public Static Object Hostcontext ... { Get ... {Illogicalcallcontext context1 = Thread. currentthread. getillogicalcallcontext (); Object Obj1 = Context1.hostcontext; If (Obj1 = Null ) ... {Logicalcallcontext context2=Callcontext. getlogicalcallcontext (); obj1=Context2.hostcontext ;} Return Obj1 ;} }
Apparently, non-web application httpcontext. Current returns NULL because
Contextbase. Current as httpcontext, return null.
Contextbase. Current has a value, but because it is not a web application, the returned object cannot be converted to httpcontext, and null is returned.
Therefore, httpcontext. Current. cache can only be used for the cache of Web applications. It is closely related to httpcontext.
3. httpruntime. cache can be used for caching non-web applications.
For example, the following ConsoleProgramCan read and write the cache normally. Httpcontext. cache cannot be used here.
Static Void Main ( String [] ARGs) ... {System. Web. caching. cache C = System. Web. httpruntime. cache; If (C ! = Null ) ... {C. insert ("1","123141432432");ObjectO=C. Get ("1"); Console. writeline (o );} Console. Readline ();}
Conclusion,
1. httpruntime. cache is equivalent to a specific implementation class of cache, which is placed in the system. Web namespace. However, non-Web applications can also be used.
2. httpcontext. cache is the encapsulation of the preceding cache class. Because it is encapsulated in httpcontext, it can only be used in httpcontext, that is, it can only be used for Web applications.
To sum up, use httpruntime. cache instead of httpcontext. cache as much as possible.