C # Cache Introduction Caching General Help class code collation. NET several cache overview __.net

Source: Internet
Author: User
Tags memory usage

Cache Overview and usage and help classes:

Cache is caching. So how does cache improve system performance and speed of operation? It is possible to improve performance with cache under any circumstances. The more you use the cache, the better.
How does the Cache work?
The Cache is a public memory slice assigned to the server.
The so-called public refers to the cache as long as the creation of any client browser can be accessed through the background code to it, it is aimed at all users, relatively session is also a piece of memory on the server, but he is oriented to a single user. It is a block of memory for the server, which means that each cache is created to occupy the server resource. So from this point we can say: not the more the cache the better.
Cache has a time limit, exceeding the expiration time set by the server, and it will be reclaimed by the server.
Cache can store any object

The cache supports boxing/unboxing operations. If you can save a DataSet object DS via Cache.Insert ("Dscache", DS) to the Cache, you can access it by unpacking the DataSet ds = (DataSet) cache["Dscache"].

Cache is generally used for data more fixed, used more frequently in the place.

There is a time limit to the cache. exceeds the expiration time of the server setting, it is reclaimed by the server. When the cache is reclaimed, the corresponding block of memory is emptied and the null value is returned when the object is accessed again via cache["CacheKey".


The importance of caching in Web sites is unquestionable. I think a lot of. NET developers in the development of Web applications, the priority is to use the cache is not a third-party caching solution (such as distributed cache memcached, Redis, etc.), but the. NET Framework has provided a variety of caching solutions. Let's talk about the understanding of caching in the. NET Framework.
1, System.Web.Caching.Cache

It is estimated that most people who have done asp.net development have used the cache under this namespace, and we can use the HttpContext.Current.Cache instance directly instead of instantiating it. Of course, the cache class under this namespace allows you to instantiate, and you need to customize your own caching system to completely control how you initialize the class. I've seen it in the garden. There are many articles about Cache the Crud helper class libraries are mostly for System.Web.Caching.Cache.

It should be explained that we can also implement the caching under different representations of Web, console, WinForm and so on through the Httpruntime.cache in this namespace, and do not need to instantiate it ourselves at all. Httpruntime.cache is one of the more classes used in personal development, and now prefers the enhanced cache class MemoryCache in. NET framework4.0.

2. Output Cache

As we all know, output caching is mainly divided into page output caching and page partial caching. The plain thing is that caching an entire page of HTML or some HTML is nothing to discuss.

3, System.Runtime.Caching

The most commonly used class memorycache in development is derived from this namespace, and you need to refer to the using System.Runtime.Caching before you use it. MemoryCache inherits from ObjectCache, IEnumerable, IDisposable, where ObjectCache is an abstract class. People who have used MemoryCache know that this memorycache has a property called Default, which can often be used as follows:

private static ObjectCache MemCache = Memorycache.default;
Of course, we can also initialize the cached object through the public memorycache (string name, NameValueCollection config = null) constructor.

We can then configure the Memory usage quota scheme and the quota check cycle for each MemoryCache instance to run in the Web.config file, and the following examples refer to MSDN:

<system.runtime.caching>
<memoryCache>
<namedCaches>
<add name= "Default" cachememorylimitmegabytes= "10″pollinginterval=" 00:02:00″/>
</namedCaches>
</memoryCache>
</system.runtime.caching>

The implication of these configurations is that you can explicitly specify the memory usage quota scheme and the quota check cycle that each MemoryCache instance runs. For example, we can configure to change the memory quota of the Memorycache.default instance on demand (not knowing the maximum memory available for the cache, or perhaps the legendary 800M or so). The cache expiration policy is much the same as other caching frameworks, unlike System.Web.Caching.Cache, which is called ChangeMonitor and provides a caching-dependent policy based on files and directories, rather than the name CacheDependency. There is also a need to explore the cache expiration strategy, although personal development is more biased towards data caching and substitution, and there is currently no contact and use of a more perfect expiration strategy solution.


here are the Help classes:

Using System;
Using System.Collections;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.Caching;
Using System.Web.Hosting; Namespace ECS. Utility {///<summary>///Caching Summary description///</summary> public class Cachehelper {///<summary>///
Gets the cache value for the current application-specified CacheKey///</summary>///<param name= "CacheKey" >///<returns></returns>y public static Object GetCache (String cachekey) {System.Web.Caching.Cache objcache = Httpruntime.cache; return objcache[c
Achekey]; ///<summary>///Set cache value for the current application specified CacheKey///</summary>///<param name= "CacheKey" >///<param  Name= "Objobject" > public static void Setcache (String CacheKey, Object objobject) {System.Web.Caching.Cache Objcache =
Httpruntime.cache;
Objcache.insert (CacheKey, objobject);  ///<summary>///Set cache value for the current application specified CacheKey///</summary>///<param name= "CacheKey" >///<param Name= "Objobject" > Publicstatic void Setcache (String CacheKey, Object Objobject, DateTime absoluteexpiration, TimeSpan slidingexpiration) {System .
Web.Caching.Cache Objcache = Httpruntime.cache;
Objcache.insert (CacheKey, objobject, NULL, absoluteexpiration, slidingexpiration); ///<summary>///Set data cache///</summary> public static void Setcache (String Cac  Hekey, object objobject, int timeout = 7200) {try {if (Objobject = null)  
              Return  
             var objcache = Httpruntime.cache; Relative expiration//objcache.insert (CacheKey, objobject, NULL, DateTime.MaxValue, timeout, Cacheitempriority.notremova  
              ble, NULL); Absolute Expiration Time Objcache.insert (CacheKey, objobject, NULL, DateTime.Now.AddSeconds (timeout), TimeSpan.Zero, Cachei  
          Tempriority.high, NULL);  
          catch (Exception) {//throw; }}///<summary>///clearSingle key cache///</summary>///<param name= "key" > public static void Removekeycache (string cachekey) {try {System.
Web.Caching.Cache Objcache = Httpruntime.cache;
Objcache.remove (CacheKey); The catch {}}///<summary>///clears all cached///</summary> public static void Removeallcache () {System.Web.Cachin
G.cache _cache = Httpruntime.cache; IDictionaryEnumerator cacheenum = _cache.
GetEnumerator (); if (_cache. Count > 0) {ArrayList al = new ArrayList (); while (Cacheenum.movenext ()) {al.
ADD (Cacheenum.key); foreach (String key in AL) {_cache.
Remove (key);  
        {}}}///<summary>///clears all caches///</summary> public static void Removeallcache () {  
        var cache = Httpruntime.cache; var cacheenum = cache.  
        GetEnumerator (); while (Cacheenum.movenext ()) {cache.  
        Remove (CacheEnum.Key.ToString ()); }///<summary>///returns all existing cache///</summary>///<returns></ret as a listurns> public static ArrayList Showallcache () {ArrayList Al = new ArrayList ();
System.Web.Caching.Cache _cache = Httpruntime.cache; if (_cache. Count > 0) {idictionaryenumerator cacheenum = _cache.
GetEnumerator (); while (Cacheenum.movenext ()) {al.
ADD (Cacheenum.key);
} return to Al; }


}
}


C # caching is primarily designed to improve the reading speed of data. Because of the traffic bottleneck between the server and the application client, when reading the bulk data, using caching to directly serve the client can reduce the data interaction between client and server, thus greatly improving the performance of the program.

the difference between cache and Session,cookie:

Session to save the data on the server side, each user has their own session, and others do not conflict that is
, you login system, your information (such as account number, password, etc.) will be saved in a separate session on the server, When you exit the system, the server will lose this session, your data will be gone, you must log on again, if the landing timeout will be thrown away, to see how the system is set up
cookies with the same session is to save your personal information, but save in the client, Which is the computer you use, and will not be thrown away unless you delete the browser cookie
Session and cookies are intended for individual users, and cache is for all users.
End ...



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.