zoukankan      html  css  js  c++  java
  • 最简单的Cache

    using System;
    using System.Collections.Generic;

    namespace DomainBase
    {
       
    public class ObjectCache
        {
           
    //Dictionary<K,T> 会自动维护一个空链表来保存不用的单元。
           
    //这里,使用被缓存对象的“弱引用”,允许这些对象被垃圾回收。

           
    private Dictionary<string, WeakReference> Buffer = new Dictionary<string, WeakReference>();

           
    public object this[string key]
            {
               
    get
                {
                    WeakReference ret;
                   
    if (Buffer.TryGetValue(key, out ret) && ret.IsAlive)
                       
    return ret.Target;
                   
    else
                       
    return null;
                }
               
    set
                {
                    WeakReference ret;
                   
    if (Buffer.TryGetValue(key, out ret))
                        ret.Target
    = value;
                   
    else
                        Buffer.Add(key,
    new WeakReference(value));
                }
            }

           
    public void Remove(string key)
            {
                Buffer.Remove(key);
            }
        }
    }



    这就是最简单的Cache。例如:

    public Class User
    {
        static ObjectCache Buffer=new ObjectCache();

        public static GetUser(string id)
        {
          User ret=Buffer[id];
          if(ret==null)
          {
                ret=读取数据库产生User对象(id);
                Buffer[id]=ret;
          }
          return ret;
        }
    版权说明

      如果标题未标有<转载、转>等字则属于作者原创,欢迎转载,其版权归作者和博客园共有。
      作      者:温景良
      文章出处:http://wenjl520.cnblogs.com/  或  http://www.cnblogs.com/

  • 相关阅读:
    node中express的中间件之basicAuth
    python练习1--用户登入
    python基础4--文件操作
    python基础3--字符串
    python基础2--字典
    python基础1--列表
    XP下使用IIS访问asp出现无权查看网页问题的解决办法
    jQueryUI Datepicker的使用
    FileUpload控件使用初步
    HTML中表格元素TABLE,TR,TD及属性的语法
  • 原文地址:https://www.cnblogs.com/wenjl520/p/1407344.html
Copyright © 2011-2022 走看看