首页 > 开发 > 综合 > 正文

前几天看IBuySpy时记在OneNote里面的笔记

2020-02-03 16:30:17
字体:
来源:转载
供稿:网友

ibuyspy portal 中使用 portalmodulecontrol 这个继承自usercontrol的类来作为站点中所有module的基类,用户控件的工作方式是,当页面上实例化一个用户控件时,自动将它的所有子控件全部render成html,然后输出,为了提高module的工作效率,每个module可以设置自己的缓存时间,在缓存时间内,系统不会再重复render它的所有子控件,而是在第一次render的时候,把结果html文本缓存起来,当下次需要的时候再直接输出。
  
  
  
  实现缓存功能,ibuyspy是通过cachedportalmodulecontrol实现的。
  
  
  
  因为ibuyspy页面上的module都是通过loadcontrol()方法来动态载入到页面上的,像这样:
  
  
  
  portalmodulecontrol portalmodule = (portalmodulecontrol) page.loadcontrol(_modulesettings.desktopsrc);
  
  
  
  portalmodule.portalid = portalsettings.portalid;
  portalmodule.moduleconfiguration = _modulesettings;
  
  
  
  parent.controls.add(portalmodule);
  
  
  
  当检测到一个module的cachetime>0时,代码则:
  
  
  
  cachedportalmodulecontrol portalmodule = new cachedportalmodulecontrol();
  
  
  
  portalmodule.portalid = portalsettings.portalid;
  portalmodule.moduleconfiguration = _modulesettings;
  
  
  
  parent.controls.add(portalmodule);
  
  
  
  就是说,代码不会再载入portalmodulecontrol类型的控件了,而是载入cachedportalmodulecontrol来实现的。
  
  
  
  下面看看cachedportalmodulecontrol是如何实现缓存的:
  
  
  
  private string _cachedoutput = "";
  
  
  
  这里定义了一个string变量,保存缓存的内容
  
  
  
  protected override void createchildcontrols() {
  
  
  
  if (_moduleconfiguration.cachetime > 0) {
  
  _cachedoutput = (string) context.cache[cachekey];
  
  }
  
  
  
  createchildcontrols()这个方法是在control类每次被实例化时,都会执行的方法。首先检查这个module是否启用了缓存,如果启用了,则从context.cache中寻找缓存,并载入到_cachedoutput中。
  
  (cachedportalmodulecontrol实质上是一个composite control,有关复合控件的相关资料,参阅:
  
  ms-help://ms.vscc.2003/ms.msdnqtr.2003feb.2052/cpguide/html/
  cpcondevelopingcompositecontrols.htm)
  
  
  
  if (_cachedoutput == null) {
  
  
  
  base.createchildcontrols();
  
  
  
  portalmodulecontrol module = (portalmodulecontrol) page.loadcontrol(_moduleconfiguration.desktopsrc);
  
  
  
  module.moduleconfiguration = this.moduleconfiguration;
  
  module.portalid = this.portalid;
  
  
  
  this.controls.add(module);
  
  }
  
  
  
  如果_cachedoutput为null,那么说明还没有缓存,于是调用base.createchildcontrols(),然后用loadcontrol()方法重新(真实的)载入控件,并把这个控件放入本控件的子控件树中。
  
  
  
  protected override void render(htmltextwriter output) {
  
  
  
  if (_moduleconfiguration.cachetime == 0) {
  
  base.render(output);
  
  return;
  
  }
  
  
  
  现在到了render方法,这个方法用于输出控件的html,首先检查是否启用缓存,如果没有,直接调用base.render()直接输出,然后return。
  
  
  
  if (_cachedoutput == null) {
  
  
  
  textwriter tempwriter = new stringwriter();
  
  base.render(new htmltextwriter(tempwriter));
  
  _cachedoutput = tempwriter.tostring();
  
  
  
  context.cache.insert(cachekey, _cachedoutput, null, datetime.now.addseconds(_moduleconfiguration.cachetime), timespan.zero);
  
  }
  
  
  
  如果启用了缓存,但是用来保存缓存内容的变量为null,那么就调用base.render()方法,把所有应该输出的html输出到_cachedoutput变量中,然后把这个变量的内容放入context.cache中。
  
  
  
  output.write(_cachedoutput);
  
  
  
  最后,把这个变量中的html内容输出。 
  
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表