UserControl cache processing in Asp. Net

Source: Internet
Author: User

In ASP. in. net, all classes inherited from usercontrol can be dynamically loaded using the load () method. The following class implements cache processing for them to improve access speed and performance. The following code snippet completes this function.

1 using system;
2 using system. IO;
3 using system. Web;
4 using system. Web. UI;
5 using system. Web. UI. webcontrols;
6 using system. componentmodel;
7
8 namespace Web
9 {
10 public class cachedcontrol: Control
11 {
12 private int _ cachetime;
13 private string _ cachedoutput;
14 private string _ cachekey;
15 private string _ componenturl;
16
17 public CachedControl (string componentGuid, string componentUrl, int cacheTime)
18 {
19 this. _ componentUrl = componentUrl;
20 this. _ cacheTime = cacheTime;
21 this. _ cacheKey = componentGuid;
22}
23
24 protected override void CreateChildControls ()
25 {
26 if (this. _ cacheTime> 0)
27 {
28 this. _ cachedOutput = (String) Context. Cache [_ cacheKey];
29}
30
31 if (this. _ cachedOutput = null)
32 {
33 base. CreateChildControls ();
34
35 UserControl comp = Page. LoadControl (_ componentUrl) as UserControl;
36 this. Controls. Add (comp );
37}
38}
39
40 protected override void Render (HtmlTextWriter output)
41 {
42 if (this. _ cacheTime = 0)
43 {
44 base. Render (output );
45}
46 else if (this. _ cachedOutput = null)
47 {
48 TextWriter tempWriter = new StringWriter ();
49 base. Render (new HtmlTextWriter (tempWriter ));
50 this. _ cachedOutput = tempWriter. ToString ();
51 context. cache. insert (_ cachekey, _ cachedoutput, null, datetime. Now. addseconds (_ cachetime), timespan. Zero );
52}
53
54 output. Write (_ cachedoutput );
55}
56}
57}
58

In the constructor, when the user component guid, URL, and cachetime are input and the component is dynamically loaded, the cache loss time of the component can be controlled, which is convenient.

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.