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.