C#中一个好的线程安全单例通用模板模式是什么

时间:2008-09-19 06:41:08

标签: c# design-patterns

我有以下C#单例模式,有什么方法可以改进它吗?

    public class Singleton<T> where T : class, new()
    {

        private static object _syncobj = new object();
        private static volatile T _instance = null;
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncobj)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                        }
                    }
                }
                return _instance;
            }
        }

        public Singleton()
        { }

    }

首选用法示例:

class Foo : Singleton<Foo> 
{
} 

相关

An obvious singleton implementation for .NET?

22 个答案:

答案 0 :(得分:17)

根据Jon Skeet在Implementing the Singleton Pattern in C#中,您发布的代码实际上被认为是错误的代码,因为在根据ECMA CLI标准进行检查时它似乎已损坏。

还要注意:每次使用新类型的T实例化对象时,它都会成为另一个实例;它没有反映在原来的单身人士身上。

答案 1 :(得分:9)

由Judith Bishop提供,http://patterns.cs.up.ac.za/

这种单例模式实现可确保延迟初始化。

//  Singleton PatternJudith Bishop Nov 2007
//  Generic version

public class Singleton<T> where T : class, new()
{
    Singleton() { }

    class SingletonCreator
    {
        static SingletonCreator() { }
        // Private object instantiated with private constructor
        internal static readonly T instance = new T();
    }

    public static T UniqueInstance
    {
        get { return SingletonCreator.instance; }
    }
}

答案 2 :(得分:9)

此代码无法编译,您需要在T上使用“类”约束。

此外,此代码需要目标类上的公共构造函数,这对单例不利,因为您无法在编译时控制仅通过Instance属性(或字段)获取(单个)实例。如果你没有除Instance之外的任何其他静态成员,你可以这样做:

class Foo
{
  public static readonly Instance = new Foo();
  private Foo() {}
  static Foo() {}
}

它是线程安全的(由CLR保证)和lazy(实例是在首次访问类型时创建的)。有关BeforeFieldInit的更多讨论以及我们在此需要静态构造函数的原因,请参阅https://csharpindepth.com/articles/BeforeFieldInit

如果您希望在类型上拥有其他公共静态成员,但仅在访问Instance时创建对象,则可以创建嵌套类型,如https://csharpindepth.com/articles/Singleton

答案 3 :(得分:6)

这是我使用.NET 4的观点

public class Singleton<T> where T : class, new()
    {
        Singleton (){}

        private static readonly Lazy<T> instance = new Lazy<T>(()=> new T());

        public static T Instance { get { return instance.Value; } } 
    }

答案 4 :(得分:3)

有关此答案的更多详细信息,请参阅其他主题:How to implement a singleton in C#?

但该主题不使用 通用

答案 5 :(得分:2)

我认为你真的不想“刻录你的基类”,这样你就可以保存2行代码。你真的不需要一个基类来实现单例。

每当你需要一个单身人士时,就这样做:

class MyConcreteClass
{
  #region Singleton Implementation

    public static readonly Instance = new MyConcreteClass();

    private MyConcreteClass(){}

  #endregion

    /// ...
}

答案 6 :(得分:1)

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

   private Singleton(){}

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

no ambiguity in .NET around initialization order;但这会引发线程问题。

答案 7 :(得分:1)

Microsoft here提供的双重检查锁定[Lea99]习惯用法与您提供的代码非常相似,遗憾的是,这不符合ECMA CLI标准的纯粹线程安全代码视图,可能无法正常工作在所有情况下。

在多线程程序中,不同的线程可以尝试同时实例化一个类。因此,依赖于if语句检查实例是否为null 的Singleton实现将不是线程安全的。不要写那样的代码!

创建线程安全单例的一种简单而有效的方法是使用嵌套类来实例化它。以下是惰性实例化单例的一个示例:

public sealed class Singleton
{ 
   private Singleton() { }

   public static Singleton Instance
   {
      get
      {
         return SingletonCreator.instance;
      }
   }

   private class SingletonCreator
   {
      static SingletonCreator() { }
      internal static readonly Singleton instance = new Singleton();
   }
}

用法:

Singleton s1 = Singleton.Instance;
Singleton s2 = Singleton.Instance;
if (s1.Equals(s2))
{
    Console.WriteLine("Thread-Safe Singleton objects are the same");
}

通用解决方案:

public class Singleton<T>
    where T : class, new()
{
    private Singleton() { }

    public static T Instance 
    { 
        get 
        { 
            return SingletonCreator.instance; 
        } 
    } 

    private class SingletonCreator 
    {
        static SingletonCreator() { }

        internal static readonly T instance = new T();
    }
}

用法:

class TestClass { }

Singleton s1 = Singleton<TestClass>.Instance;
Singleton s2 = Singleton<TestClass>.Instance;
if (s1.Equals(s2))
{
    Console.WriteLine("Thread-Safe Generic Singleton objects are the same");
}

最后,这是一个有点相关且有用的建议 - 为了帮助避免使用lock关键字可能导致的死锁,请考虑添加以下属性以帮助仅使用公共静态方法保护代码:

using System.Runtime.CompilerServices;
[MethodImpl (MethodImplOptions.Synchronized)]
public static void MySynchronizedMethod()
{
}

参考文献:

  1. C#Cookbook(O'Reilly),Jay Hilyard&amp; Stephen Teilhet
  2. C#3.0设计模式(O'Reilly),Judith Bishop
  3. CSharp-Online.Net - 单例设计模式:线程安全的Singleton

答案 8 :(得分:1)

尝试使用这个通用的Singleton类,以线程安全和懒惰的方式实现Singleton设计模式(thx到wcell)。

public abstract class Singleton<T> where T : class
{
    /// <summary>
    /// Returns the singleton instance.
    /// </summary>
    public static T Instance
    {
        get
        {
            return SingletonAllocator.instance;
        }
    }

    internal static class SingletonAllocator
    {
        internal static T instance;

        static SingletonAllocator()
        {
            CreateInstance(typeof(T));
        }

        public static T CreateInstance(Type type)
        {
            ConstructorInfo[] ctorsPublic = type.GetConstructors(
                BindingFlags.Instance | BindingFlags.Public);

            if (ctorsPublic.Length > 0)
                throw new Exception(
                    type.FullName + " has one or more public constructors so the property cannot be enforced.");

            ConstructorInfo ctorNonPublic = type.GetConstructor(
                BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], new ParameterModifier[0]);

            if (ctorNonPublic == null)
            {
                throw new Exception(
                    type.FullName + " doesn't have a private/protected constructor so the property cannot be enforced.");
            }

            try
            {
                return instance = (T)ctorNonPublic.Invoke(new object[0]);
            }
            catch (Exception e)
            {
                throw new Exception(
                    "The Singleton couldnt be constructed, check if " + type.FullName + " has a default constructor", e);
            }
        }
    }
}

答案 9 :(得分:1)

:/ Judith bishop的通用“singleton”模式似乎有点瑕疵,它总是可以创建T类型的几个实例,因为构造函数必须公开才能在这个“模式”中使用它。在我看来,它与singleton完全无关,它只是一种工厂,它总是返回相同的对象,但不会使它成为单例...只要一个类的实例可以超过1个它不能成为单身人士。这种模式的最高等级是什么原因?

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

  private Singleton()
  {
  }

  public static Singleton Instance
  {
    get
    {
      return _instance;
    }
  }
}

静态初始化程序被认为是线程安全的...我不知道但是你根本不应该使用单例的成语,如果你将我的代码包装在不超过3行的上面...并且从单例继承没有任何意义

答案 10 :(得分:1)

根据要求,将我原来的答案交叉发布到另一个问题。

我的版本使用Reflection,与派生类中的非公共构造函数一起使用,线程安全(显然)与惰性实例化(根据我在下面找到的文章):

public class SingletonBase<T> where T : class
{
    static SingletonBase()
    {
    }

    public static readonly T Instance = 
        typeof(T).InvokeMember(typeof(T).Name, 
                                BindingFlags.CreateInstance | 
                                BindingFlags.Instance |
                                BindingFlags.Public |
                                BindingFlags.NonPublic, 
                                null, null, null) as T;
}

几年前我选择了这个,不知道我有多少,但谷歌搜索代码可能会找到技术的原始来源,如果它不是我。

这是我发布的oldest source of the code that I can find

答案 11 :(得分:1)

我一直在寻找更好的Singleton模式,并喜欢这个。所以把它移植到VB.NET,对其他人有用:

Public MustInherit Class Singleton(Of T As {Class, New})
    Public Sub New()
    End Sub

    Private Class SingletonCreator
        Shared Sub New()
        End Sub
        Friend Shared ReadOnly Instance As New T
    End Class

    Public Shared ReadOnly Property Instance() As T
        Get
            Return SingletonCreator.Instance
        End Get
    End Property
End Class

答案 12 :(得分:0)

再次...... pff ...... :) 我对确保按需创建实例数据的贡献:


/// <summary>Abstract base class for thread-safe singleton objects</summary>
/// <typeparam name="T">Instance type</typeparam>
public abstract class SingletonOnDemand<T> {
  private static object __SYNC = new object();
  private static volatile bool _IsInstanceCreated = false;
  private static T _Instance = default(T);

  /// <summary>Instance data</summary>
  public static T Instance {
    get {
      if (!_IsInstanceCreated)
        lock (__SYNC)
          if (!_IsInstanceCreated) {
            _Instance = Activator.CreateInstance<T>();
            _IsInstanceCreated = true;
          }
          return _Instance;
    }
  }
}

答案 13 :(得分:0)

我对确保按需创建实例数据的贡献:


/// <summary>Abstract base class for thread-safe singleton objects</summary>
/// <typeparam name="T">Instance type</typeparam>
public abstract class SingletonOnDemand<T> {
    private static object __SYNC = new object();
    private static volatile bool _IsInstanceCreated = false;
    private static T _Instance = default(T);

/// <summary>Instance data</summary> public static T Instance { get { if (!_IsInstanceCreated) lock (__SYNC) if (!_IsInstanceCreated) _Instance = Activator.CreateInstance<T>(); return _Instance; } } }

答案 14 :(得分:0)

public static class LazyGlobal<T> where T : new()
{
    public static T Instance
    {
        get { return TType.Instance; }
    }

    private static class TType
    {
        public static readonly T Instance = new T();
    }
}

// user code:
{
    LazyGlobal<Foo>.Instance.Bar();
}

或者:

public delegate T Func<T>();

public static class CustomGlobalActivator<T>
{
    public static Func<T> CreateInstance { get; set; }
}

public static class LazyGlobal<T>
{
    public static T Instance
    {
        get { return TType.Instance; }
    }

    private static class TType
    {
        public static readonly T Instance = CustomGlobalActivator<T>.CreateInstance();
    }
}

{
    // setup code:
    // CustomGlobalActivator<Foo>.CreateInstance = () => new Foo(instanceOf_SL_or_IoC.DoSomeMagicReturning<FooDependencies>());
    CustomGlobalActivator<Foo>.CreateInstance = () => instanceOf_SL_or_IoC.PleaseResolve<Foo>();
    // ...
    // user code:
    LazyGlobal<Foo>.Instance.Bar();
}

答案 15 :(得分:0)

前一段时间看过一个使用反射访问私有(或公共)默认构造函数的文件:

public static class Singleton<T>
{
    private static object lockVar = new object();
    private static bool made;
    private static T _singleton = default(T);

    /// <summary>
    /// Get The Singleton
    /// </summary>
    public static T Get
    {
        get
        {
            if (!made)
            {
                lock (lockVar)
                {
                    if (!made)
                    {
                        ConstructorInfo cInfo = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
                        if (cInfo != null)
                            _singleton = (T)cInfo.Invoke(new object[0]);
                        else
                            throw new ArgumentException("Type Does Not Have A Default Constructor.");
                        made = true;
                    }
                }
            }

            return _singleton;
        }
    }
}

答案 16 :(得分:0)

我将此提交给小组。它似乎是线程安全的,通用的并遵循模式。你可以继承它。这是从其他人所说的拼凑而成的。

public class Singleton<T> where T : class
{
    class SingletonCreator
    {
        static SingletonCreator() { }

        internal static readonly T Instance =
            typeof(T).InvokeMember(typeof(T).Name,
                                    BindingFlags.CreateInstance |
                                    BindingFlags.Instance |
                                    BindingFlags.Public |
                                    BindingFlags.NonPublic,
                                    null, null, null) as T;
    }

    public static T Instance
    {
        get { return SingletonCreator.Instance; }
    }
}

预期实施:

public class Foo: Singleton<Foo>
{
     private Foo() { }
}

然后:

Foo.Instance.SomeMethod();

答案 17 :(得分:0)

我非常喜欢你的原始答案 - 唯一缺少的东西(根据blowdart发布的链接)是使_instance变量变为volatile,以确保它实际上已经设置在锁中。 当我必须使用单例时,我实际上使用了blowdart解决方案,但我没有任何需要进行后期实例化等。

答案 18 :(得分:0)

wikipedia中一样:

  

单例模式是限制的模式   将类实例化为一个对象

我认为没有保证使用泛型的方法,如果你限制了单例本身的实例化,如何限制主类的实例化,我认为不可能这样做,并且实现这个简单的模式并不难,采用这种方式使用静态构造函数和私有集:

public class MyClass
{
        private MyClass()
        {

        }

        static MyClass()
        {
            Instance = new MyClass();
        }

        public static MyClass Instance { get; private set; }
}

OR:

public class MyClass
    {
            private MyClass()
            {

            }

            static MyClass()
            {
                Instance = new MyClass();
            }

            private static MyClass instance;



            public static MyClass Instance
            {
                get
                {
                    return instance;
                }
                private set
                {
                    instance = value;
                }
            }
    }

答案 19 :(得分:0)

这对我有用:

public static class Singleton<T> 
{
    private static readonly object Sync = new object();

    public static T GetSingleton(ref T singletonMember, Func<T> initializer)
    {
        if (singletonMember == null)
        {
            lock (Sync)
            {
                if (singletonMember == null)
                    singletonMember = initializer();
            }
        }
        return singletonMember;
    }
}

用法:

private static MyType _current;
public static MyType Current = Singleton<MyType>.GetSingleton(ref _current, () => new MyType());

消耗单身人士:

MyType.Current. ...

答案 20 :(得分:0)

没有关系,请始终使用Parallel.For检查并发性! (其中迭代可以并行运行的循环)

放入Singleton C'tor:

 private Singleton ()
        {
            Console.WriteLine("usage of the Singleton for the first time");
        }

输入Main:

Parallel.For(0, 10,
              index => {
                  Thread tt = new Thread(new ThreadStart(Singleton.Instance.SomePrintMethod));
                  tt.Start();
              });

答案 21 :(得分:-8)

你并不需要这一切,C#已经内置了一个好的单例模式。

static class Foo

如果你需要比这更有意思的东西,那么你的新单身人士可能会变得与你的通用模式一样无用。

编辑:通过“更有趣”,我包括继承。如果你可以继承单身人士,那么它就不再是单身人士了。