zoukankan      html  css  js  c++  java
  • Asp.net下的Singleton模式

    现在大多数虚拟主机的内存回收策略非常变态,例如万网平均10分钟就会回收一次内存,而西部数码更是1分钟清一次。

    这样使用传统的思路吧数据保存在内存里就会失败(惨痛的教训,调试了半天终于发现)。

    如果使用了传统的Singleton模式,那么本质上singleton就不存在了,仍然是每次新建。

    传统Singleton:

        public class ClassicSingleton
        {
            
    private static ClassicSingleton instance;
            
    public static ClassicSingleton Instance
            {
                
    get
                {
                    
    lock (typeof(ClassicSingleton))
                    {
                        
    if (instance == null)
                            instance 
    = new ClassicSingleton();
                        
    return instance;
                    }
                }
            }

        }


    为了解决上面的问题,我把数据保存在Application里面,成为针对Asp.net的singleton:

        public class AspNetSingleton
        {
            
    private const string cacheid = ".aspnetsingleton";

            
    private static AspNetSingleton instance;
            
    public static AspNetSingleton Instance
            {
                
    get
                {
                    
    lock (typeof(AspNetSingleton))
                    {
                        AspNetSingleton cache 
    = HttpContext.Current.Application[cacheid] as AspNetSingleton;

                        
    if (cache == null)
                        {
                            cache 
    = new AspNetSingleton();

                            HttpContext.Current.Application[cacheid] 
    = cache;
                        }

                        
    return cache;
                    }
                }
            }
        }
  • 相关阅读:
    spring cloud 学习
    python学习-2 python安装和环境变量的设置
    python学习-1 编程语言的介绍
    LIUNX随堂学习-3 权限
    LIUNX随堂学习-2 用户和组,增、删、改、查
    LIUNX随堂学习-1 用户及查看信息
    MySQL--Oracle导出数据csv
    MySQL--mysql中You can’t specify target table for update in FROM clause错误解决方法
    Python--安装
    MySQL--复制
  • 原文地址:https://www.cnblogs.com/zc22/p/1245998.html
Copyright © 2011-2022 走看看