1

如果我在 asp.net 中的集合周围有一个单例包装器,它是否必须被缓存,或者它的数据是否会在回发中持久保存?

此外,如果另一个用户登录到应用程序,该应用程序是否会创建另一个实例(自身),从而创建另一个单例实例,还是会访问在第一个实例中创建的同一个单例?

单例的实际实现是以下之一:(设计1:)

using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}

或设计 2:

public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();

   private Singleton(){}

   public static Singleton Instance
   {
      get 
      {
         return instance; 
      }
   }
}
4

2 回答 2

4

只要应用程序正在运行,静态变量就会存在,直到应用程序重新启动。它将存在于回发和用户中。

本文展示了如何实现静态单例:http: //msdn.microsoft.com/en-us/library/ff650316.aspx

您是否有任何其他要求会影响单例的实施?

于 2011-01-07T18:03:32.120 回答
2

Singleton is pattern that makes sure there is only one instance for all request. Since you have declared it static it exists for lifetime of the application. And the same instance will be returned to any user requesting the object through your property.

于 2011-01-07T18:29:52.600 回答