自写Asp.Net中的UserControl缓存处理
在Asp.Net中,继承自UserControl的类,都可以使用Load()的方法动态加载,下面这个类要对其其实现缓存处理,以用来提高访问速度和性能。下面的片断代码完成了此功能。
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
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 Web9
{10
public class CachedControl : Control11
{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

其中,在构造函数中,传入了用户组件Guid,Url,CacheTime,动态加载组件时,就可以控制该组件的缓存丢失时间,很方便。


浙公网安备 33010602011771号