The cache can be conveniently used in ASP. NET. For cache, there are generally two methods to call: httpcontext. cache and httpruntime. cache. So what are the differences between the two types of cache?
Let's take a look at the notes on msdn:
Httpruntime. cache: Get the current applicationProgram.
Httpcontext. cache: gets the cache object for the current HTTP request.
Does it mean that httpruntime. cache is at the application level, while httpcontext. cache is for each user? No. In fact, the two call the same object. The difference is that the calling method is different (as far as I know ).
Facts are better than words. Write an example to prove it:
/**/ /// <Summary> /// Use httpruntime. cache to save the cache /// </Summary> Private Void Btnhttpruntimecachesave_click ( Object Sender, system. eventargs E) ... {Httpruntime. cache. insert (cachekey, cachevalue, Null , Datetime. Now. addminutes ( 3 ), Timespan. Zero );} /**/ /// <Summary> /// Use httpruntime. cache to read the cache /// </Summary> Private Void Btnhttpruntimecacheload_click ( Object Sender, system. eventargs E) ... { If (Httpruntime. cache [cachekey] = Null ) ... {Cachecontent = " No Cache " ;} Else ... {Cachecontent = ( String ) Httpruntime. cache [cachekey];} Lblcachecontent. Text = Cachecontent ;} /**/ /// <Summary> /// Use httpcontext. cache to save the cache /// </Summary> Private Void Btnhttpcontextcachesave_click ( Object Sender, system. eventargs E) ... {Httpcontext. Current. cache. insert (cachekey, cachevalue, Null , Datetime. Now. addminutes ( 3 ), Timespan. Zero );} /**/ /// <Summary> /// Use httpcontext. cache to read the cache /// </Summary> Private Void Btnhttpcontextcacheload_click ( Object Sender, system. eventargs E) ... { If (Httpcontext. Current. cache [cachekey] = Null ) ... {Cachecontent = " No Cache " ;} Else ... {Cachecontent = ( String ) Httpcontext. Current. cache [cachekey];} Lblcachecontent. Text = Cachecontent ;}
Through this example, we can easily prove that:
- The cache saved by httpcontext. cache can be read by both httpcontext. cache and httpruntime. cache.
- Both httpcontext. cache and httpruntime. cache can be read.
- No matter which user changes the cache, the content of the cache read by other users will also change.
Httpruntime. cache is equivalent to a specific cache implementation class, which is placed in the system. Web namespace. But non-Web applications can also be used (other types can also be used, such as the console ).
Httpcontext. cache is the encapsulation of the preceding cache class. Because it is encapsulated in httpcontext, it can only be used when you know httpcontext, that is, it can only be used for Web applications.