Brief discussion on the cache of optimizing ASP.net application performance

Source: Internet
Author: User
Tags datetime insert tostring
asp.net|cache| Performance | optimization

Although it is now a broadband era, the kitten has been away from us, as Web application developers, we still have the responsibility and obligation to continuously through technical means to optimize the performance of Web applications, so that users browse less wait, more readily.

Fortunately, ASP. NET as a Web development technology based on the. NET Framework, it also enjoys the advantages of the. NET Framework, the. NET Framework provides us with good cache technology, enabling us to develop faster, better user experience Web applications. Namespace System.Web.Caching provides the cache class, and its cache validity depends on the following three scenarios:

1. Point in time (valid at specified point in time);
2. Key value (key value for cache entry identification);
3. File or directory (specify file or directory changes, the original cache item is not available);

I will share with you the use of cache to improve the performance of asp.net applications.

We often encounter reading lists of records (such as the recently updated news list top N), the record itself (for example, a piece of news), and when a user accesses it, does the information always have to be read repeatedly from the database? Smart as you may know, this is completely unnecessary.

In order to facilitate processing, we design a Sitecache class (borrowed from CS CSCache.cs), and provide a number of static methods to handle the cache items to add and delete.

Code:

SiteCache.cs
1using System;
2using System.Collections;
3using System.Text.RegularExpressions;
4using system.web;
5using System.Web.Caching;
6
7namespace ycweb.components
8{
9 public class Sitecache
10 {
One private static readonly Cache _cache;
The public static readonly int dayfactor;
private static int Factor;
public static readonly int hourfactor;
public static readonly int minutefactor;
16
Static Sitecache ()
18 {
Dayfactor = 17280;
Hourfactor = 720;
Minutefactor = 12;
Factor = 5;
_cache = Httpruntime.cache;
24}
25
Private Sitecache ()
27 {
28}
29
public static void Clear ()
31 {
IDictionaryEnumerator enumerator = _cache. GetEnumerator ();
A while (enumerator. MoveNext ())
34 {
_cache. Remove (Enumerator. Key.tostring ());
36}
37}
38
$ public static object get (String key)
40 {
_cache[key];
42}
43
The public static void Insert (string key, Object obj)
45 {
Insert (key, obj, NULL, 1);
47}
48
The public static void Insert (string key, object obj, int seconds)
50 {
Wu Inserts (key, obj, null, seconds);
52}
53
The public static void Insert (string key, Object obj, CacheDependency dep)
55 {
Insert (key, obj, DEP, hourfactor*12);
57}
58
The public static void Insert (string key, object obj, int seconds, cacheitempriority priority)
60 {
Insert (key, obj, null, seconds, priority);
62}
63
The public static void Insert (string key, Object obj, cachedependency dep, int seconds)
65 {
Insert (key, obj, dep, seconds, Cacheitempriority.normal);
67}
68
public static void Insert (string key, Object obj, cachedependency dep, int seconds, cacheitempriority priority)
70 {
if (obj!= null)
72 {
_cache. Insert (key, obj, DEP, DateTime.Now.AddSeconds (double) (factor*seconds), TimeSpan.Zero, priority, NULL);
74}
75}
76
public static void Max (string key, Object obj)
78 {
Max (key, obj, null);
80}
81
The public static void Max (string key, Object obj, CacheDependency dep)
83 {
/if (obj!= null)
85 {
_cache. Insert (key, obj, DEP, DateTime.MaxValue, TimeSpan.Zero, cacheitempriority.abovenormal, NULL);
87}
88}
89
The public static void Microinsert (string key, object obj, int secondfactor)
91 {
(obj!= null)
93 {
_cache. Insert (key, obj, NULL, DateTime.Now.AddSeconds (double) (factor*secondfactor), TimeSpan.Zero);
95}
96}
97
The public static void Remove (String key)
99 {
_cache. Remove (key);
101}
102
Removebypattern static void (string pattern)
104 {
IDictionaryEnumerator enumerator = _cache. GetEnumerator ();
The regex regex1 = new Regex (Pattern, Regexoptions.singleline | regexoptions.compiled | Regexoptions.ignorecase);
The while (enumerator. MoveNext ())
108 {
109 if (regex1. IsMatch (Enumerator. Key.tostring ()))
110 {
_cache. Remove (Enumerator. Key.tostring ());
112}
113}
114}
115
116 public static void Resetfactor (int cachefactor)
117 {
118 Factor = Cachefactor;
119}
120
121
122
123}
124}

In fact, this class is mainly to use the above mentioned in the cache dependencies on the 1th and 2nd features to maintain our own cache items.

With the Sitecache class, next look at how to use it. Or read the news tonn list for example:

1public static RecordSet getnewssettopn (String Classcode,int Topn,sortpostsby by, SortOrder SortOrder, string Language
2{
3 string CacheKey = String. Format ("Newssettopn-lg:{0}:cc:{1}:tn:{2}:ob:{3}:so:{4}", Language,classcode,topn.tostring (), orderBy.ToString (), Sortorder.tostring ());
4
5//Read cache entry from context
6 Recordset Newsset = Httpcontext.current.items[cachekey] as Recordset;
7 if (Newsset = null)
8 {
9//Read cache entry from Httpruntime.cache
Newsset = Sitecache.get (CacheKey) as RecordSet;
One if (Newsset = null)
12 {
13//Read directly from the database
Commondataprovider dp=commondataprovider.instance ();
Newsset =DP. GETNEWSSETTOPN (Language,classcode,topn,orderby,sortorder);
16//And cache the results in Httpruntime.cache
Sitecache.insert (CacheKey, Newsset, cacheitempriority.normal);
18}
19
20}
21return Newsset;
22}

This allows you to read the list in 5 minutes without having to repeatedly access the database. Of course, some people will ask, if in this 5 minutes a piece of news deleted or modified how to do, it does not matter, we delete or modify the cache key can be forced to delete the cache entry, of course, If you think you are not particularly concerned about the timeliness of the list, you can not force the deletion of the cache entry, so that the time point defined by the cache is automatically invalidated. Of course, it is best to provide a way to force the deletion of the cache entry by matching pattern entries, for example:

1/**////<summary>
2///deletes the cache entry for the matching NEWSSETTOPN list
3///</summary>
4public static void Clearnewssettopncache (String language,string classcode,int topn)
5{
6 string CacheKey = string. Format ("Newssettopn-lg:{0}:cc:{1}:tn:{2}", language,classcode,topn.tostring ());
7 Sitecache.removebypattern (CacheKey);
8}
9

Call the static method Clearnewssettopncache () after publishing the news to forcibly clear the original TOPN cache entry, for example:

1/**////<summary>
2///release (new) News
3///</summary>
4///<param name= "POST" > News instance </param>
5///<returns> return Status </returns>
6public static int Create (News post)
7{
8 int status;
9 Commondataprovider dp=commondataprovider.instance ();
DP. Createupdatedeletenews (post, dataaction.create, out status);
11//Force clear matching cache entry
Clearnewssettopncache (post. Language, Post. CLASSCODE,GLOBALS.GETSITESETTING.NEWSLISTTOPN);
return status;
14}


That's all. If there are any irregularities, I hope you will correct me.



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.