Use of cache in C #

Source: Internet
Author: User
Tags server memory

The concept of caching and its advantages and disadvantages here is not much to introduce, the main introduction of the method used.

1. In ASP. Page caching is simple to use, just add a statement to the top of the ASPX page:

<%@ OutputCache duration= "" "varybyparam=" None "%>

Duration: Cache time (seconds), required attribute

2. Using Microsoft's own class library System.Web.Caching

It is not recommended to use the class library provided by Microsoft directly, as this is not a deep understanding. So here I will take you to write a cache operation method, so that understanding more clearly.

Words don't say much, the code knocks.

First, the simulation data sources first. Create a new class and write a data manipulation method (the method is time consuming and resource-intensive)

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;using System.threading.tasks;namespace cache{public    class DataSource    {//        <summary>        // Simulate reading data from a database        ///time consuming CPU//</summary>//        <param name= "Count" ></param>        public static int getdatabydb (int count)        {            Console.WriteLine ("-------getdatabydb-------");            int result = 0;            for (int i = count; i < 99999999; i++)            {                result + = i;            }            Thread.Sleep (+);            return result;}}    }

Second, write a cache operation class

2.1 Constructs a word typical container for storing cached data, with permissions set to private, preventing arbitrary access resulting in data insecurity

                 privatestatic dictionary<stringobjectnew dictionary<stringobject> ();

2.2 Constructs three methods (adds data to the cache container, fetches data from the cache container, and determines if the cache exists)

        /// <summary>        ///Add Cache/// </summary>         Public Static voidADD (stringKeyObjectvalue)        {Cachedictionary.add (key, value); }        /// <summary>        ///Get Cache/// </summary>         Public StaticT get<t> (stringkey) {            return(T) Cachedictionary[key]; }        /// <summary>        ///determine if the cache exists/// </summary>        /// <param name= "key" ></param>        /// <returns></returns>         Public Static BOOLExsits (stringkey) {            returnCachedictionary.containskey (key); }

Third, the procedure entrance writing test method

3.1 Take a look at the general situation does not apply to the cache, its execution efficiency is how slow

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacecache{classProgram {Static voidMain (string[] args) {             for(inti =1; I <6; i++) {Console.WriteLine ($"------The {i} request------"); intresult = Datasource.getdatabydb (666); Console.WriteLine ($"the data obtained for the {i} request is: {result}"); }        }    }}

3.2 Next, we write the cache trial method. The concept is simply to go to the dictionary container according to the key to find out if there is a relative cache of data, there is a direct call, not generated and stored in the dictionary container.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacecache{classProgram {Static voidMain (string[] args) {             for(inti =1; I <6; i++) {Console.WriteLine ($"------The {i} request------"); //int result = Datasource.getdatabydb (666);                intresult =0; //the name of key must ensure the accuracy of the request DataSource Getdatabydb 666 indispensable                stringKey ="datasource_getdatabydb_666"; if(Cachehelper.exsits (key)) {//cache exists, direct access to the original dataresult = cachehelper.get<int>(key); }                Else                {                    //cache does not exist, go to generate cache, and join containerresult = Datasource.getdatabydb (666);                Cachehelper.add (key, result); } Console.WriteLine ($"the data obtained for the {i} request is: {result}"); }        }    }}

3.3 Let's see how efficient it is to join the cache.

Four, can see, instantaneous completion. As it is, the use of the cache is basically complete. But come back and think about it. If a system uses caches in hundreds or thousands of places, wouldn't it be necessary to write hundreds of if else to determine if the cache exists and then get it?

The answer is obvious, certainly unreasonable. So we're going to optimize the code.

4.1 Cache Action Class (Cachehelper) writes a generic fetch method

        /// <summary>        ///Cache Fetch Method/// </summary>        /// <typeparam name= "T" ></typeparam>        /// <param name= "key" >cache dictionary container corresponding to key</param>        /// <param name= "func" >delegate method incoming action object</param>        /// <returns></returns>         Public StaticT getcache<t> (stringKey, func<t>func) {T T=default(T); if(Cachehelper.exsits (key)) {//cache exists, direct access to the original datat = cachehelper.get<t>(key); }            Else            {                //cache does not exist, go to generate cache, and join containert =func.                Invoke ();            Cachehelper.add (key, T); }            returnT; }

4.2 The program entry, the passed-in delegate parameter is the optimized code for the Lamad expression

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacecache{classProgram {Static voidMain (string[] args) {             for(inti =1; I <6; i++) {Console.WriteLine ($"------The {i} request------");                intresult =0; //the name of key must ensure the accuracy of the request DataSource Getdatabydb 666 indispensable                stringKey ="datasource_getdatabydb_666"; //write the Get data operation to be performed as a delegate incoming method (emphasis)//func<int> Func = new Func<int> (() = {return datasource.getdatabydb (666);});result= Cachehelper.getcache (key, () = Datasource.getdatabydb (666));Console.WriteLine ($"the data obtained for the {i} request is: {result}"); }        }    }}

Here, the use of the cache has basically ended. It is best to mention that the cache is used as much as possible when the volume of data is small and the number of repeated queries is large. Because the cache also consumes memory, the server memory is limited!

Related Article

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.