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;
                }
            }
        }
    }
原文地址:https://www.cnblogs.com/zc22/p/1245998.html