NET three cache mechanisms (cache usage in WinForm)

Source: Internet
Author: User

The original (http://www.cnblogs.com/wuhuacong/p/3526335.html) Thank Wu Huacong author for sharing!

In many cases, the use of caching can improve the response speed of the program, while reducing the pressure on access to specific resources. This article is mainly for their own in the WinForm cache use to do a guided introduction, I hope you can learn some of the cache usage scenarios and use of methods. Caching is a problem that must be considered in a medium-sized system. In order to avoid each request to access the background resources (such as the database), we generally consider some of the updates are not very frequent, can be reused data, in a certain way to temporarily save, the subsequent requests can be directly accessed by the situation of these saved data. This mechanism is called a caching mechanism.

The caching capabilities of. NET 4.0 consist primarily of three parts: System.runtime.caching,system.web.caching.cache and output cache.

System.Runtime.Caching This is the new caching framework in. NET 4.0, mainly using the MemoryCache object, which exists in the Assembly System.Runtime.Caching.dll.

System.Web.Caching.Cache This is a cache object that has been in. NET2.0, which is usually used mainly in the Web, but can also be used in WinForm, but to refer to System.Web.dll.

The Output cache is used in ASP., and versions prior to ASP. NET 4.0 use System.Web.Caching.Cache to cache HTML fragments directly. It was redesigned in ASP. NET 4.0, providing a outputcacheprovider for developers to extend, but it still uses System.Web.Caching.Cache to do caching by default.

1, custom hastable cache processing.

In addition to the above three kinds of caching mechanism, generally we can also in the static object through the Hashtable or dictionary way to customize the cache storage and use.

For example, in my own development of the program, all use the factory class to create business objects, because the creation of business objects and data access layer objects, is an interface or the middle layer repeatedly called operations, so it is necessary to put the frequently called object to store it, download the call, directly from the memory to be removed. The following Bllfactory class, which is a generic object-based business class creation operation, uses a Hashtable-based static object for caching.

1 /// <summary>2 ///The factory class that constructs the business class3 /// </summary>4 /// <typeparam name= "T" >business Object Type</typeparam>5  Public classBllfactory<t>whereT:class6 {7 Private StaticHashtable Objcache =NewHashtable ();8 Private Static ObjectSyncRoot =NewObject ();9 Ten /// <summary> One ///Create or get an instance of the corresponding business class from the cache A /// </summary> -  Public StaticT Instance - { the Get - { - stringCacheKey =typeof(T). FullName; -T BLL = (t) Objcache[cachekey];//read from Cache + if(BLL = =NULL) - { + Lock(syncRoot) A { at if(BLL = =NULL) - { -BLL = Reflect<t>. Create (typeof(T). FullName,typeof(T). Assembly.getname (). Name);//reflection creation, and caching -Objcache.add (typeof(T). FullName, BLL); - } - } in } - returnBLL; to } + } -}

2, use. NET4.0 the MemoryCache object implements the cache

MemoryCache's use of the internet is not much, but this is. NET4.0 the newly introduced cache object, it is estimated to replace the cache module of the original Enterprise Library, so that the. NET cache can be ubiquitous, instead of being used on a specific version of Windows.

First we use to create a memorycache-based helper class Memorycachehelper, which makes it easy to invoke cache processing.

1 /// <summary>2     ///MemoryCache-based cache helper Classes3     /// </summary>4      Public Static classMemorycachehelper5     {6         Private Static ReadOnlyObject _locker =New Object();7      8          Public StaticT getcacheitem<t> (String key, func<t> cachepopulate, TimeSpan? slidingexpiration =NULLDatetime? absoluteexpiration =NULL)9         {Ten             if(String.isnullorwhitespace (key))Throw NewArgumentException ("Invalid Cache Key"); One             if(Cachepopulate = =NULL)Throw NewArgumentNullException ("cachepopulate"); A             if(slidingexpiration = =NULL&& absoluteexpiration = =NULL)Throw NewArgumentException ("either a sliding expiration or absolute must be provided"); -       -             if(Memorycache.default[key] = =NULL) the             { -                 Lock(_locker) -                 { -                     if(Memorycache.default[key] = =NULL) +                     { -                         varitem =NewCacheItem (Key, Cachepopulate ()); +                         varPolicy =Createpolicy (slidingexpiration, absoluteexpiration); A       at MEMORYCACHE.DEFAULT.ADD (item, policy); -                     } -                 } -             } -       -             return(T) Memorycache.default[key]; in         } -       to         Private StaticCacheItemPolicy Createpolicy (TimeSpan slidingexpiration, DateTime?)absoluteexpiration) +         { -             varPolicy =NewCacheItemPolicy (); the       *             if(Absoluteexpiration.hasvalue) $             {Panax NotoginsengPolicy. absoluteexpiration =Absoluteexpiration.value; -             } the             Else if(Slidingexpiration.hasvalue) +             { APolicy. slidingexpiration =Slidingexpiration.value; the             } +       -Policy. Priority =Cacheitempriority.default; $       $             returnpolicy; -         } -}

This helper class has only one public method, that is Getcacheitem, when used, need to specify the key and the processing agent to get the data, as well as the cache expiration time, is based on the timespan or absolute time, select one.

The above auxiliary class, under what circumstances will we use it?

If the staff ID is used in a workflow module, and the personnel ID needs to be escaped the person name, the personnel information we generally know put in the Authority system module, then if in the workflow need to frequently to escape the personnel ID, then you need to call the interface module of the permission system, This process can be optimized with the caching module.

1 voidGridview1_customcolumndisplaytext (Objectsender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)2         {3             if(E.column.fieldname.equals ("Procuser") || E.column.fieldname.equals ("Procuid") || E.column.fieldname.equals ("UserId"))4             {5                 if(E.value! =NULL)6                 {7E.displaytext =Securityhelper.getuserfullname (e.value.tostring ());8                 }9             }Ten}

The securityhelper.getuserfullname is my cache-based two encapsulation of calls, as shown in the following logic.

1 /// <summary>2         ///gets the user's full name based on the user's ID and puts it in the cache3         /// </summary>4         /// <param name= "UserId" >User's ID</param>5         /// <returns></returns>6          Public Static stringGetuserfullname (stringuserId)7         {            8             stringKey ="Security_userfullname"+userId;9             stringFullName = memorycachehelper.getcacheitem<string>(Key,Ten                 Delegate() {returnBllfactory<user>. Instance.getfullnamebyid (Userid.toint32 ()); }, One                 NewTimeSpan (0, -,0));//expires in 30 minutes A             returnFullName; -}

Memorycachehelper method Getcacheitem Inside the func<t> I used an anonymous function to get the cached value.

1 Delegate return Bllfactory<user>. Instance.getfullnamebyid (Userid.toint32 ()); }

and call Bllfactory<user>. Instance.getfullnamebyid is to get the corresponding data from the database.

This will automatically invoke the method of the business object class to fetch the data the first time or when the cache expires.

Finally, in the interface call Getuserfullname method can be implemented based on the invocation of the cache, the first use of the program, encountered the specified key without data, go to the database to get, and then hit the key, then directly get the cached data.

The following figure is the program specific implementation effect.

Of course, the above two ways can also be implemented through the introduction of AOP code simplification operation, but because of AOP introduced, will involve more knowledge points, and familiar with the program is not enough, so still use the more common way to handle the cached data.

NET three cache mechanisms (cache usage in WinForm)

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.