什么是一个很好的线程安全单例通用模板模式在C# [英] What's a good threadsafe singleton generic template pattern in C#

查看:113
本文介绍了什么是一个很好的线程安全单例通用模板模式在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  public class Singleton< T>其中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()
{}

}
pre>

首选使用示例:

  class Foo:Singleton&Foo> ; 
{
}

相关 p>

.NET的一个明显的单例实现?

解决方案

根据Jon Skeet在在C#中实现单例模式,您发布的代码实际上被视为坏代码,因为根据ECMA CLI标准进行检查时,它会显示为坏。 >

还要注意:每当你用一种新的T实例化你的对象,它变成另一个实例;它不会反映在您的原始单身人士中。


I have the following C# singleton pattern, is there any way of improving it?

    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()
        { }

    }

Preferred usage example:

class Foo : Singleton<Foo> 
{
} 

Related:

An obvious singleton implementation for .NET?

解决方案

According to Jon Skeet in Implementing the Singleton Pattern in C# the code you posted is actually considered as bad code, because it appears broken when checked against the ECMA CLI standard.

Also watch out: everytime you instantiate your object with a new type of T, it becomes another instance; it doesn't get reflected in your original singleton.

这篇关于什么是一个很好的线程安全单例通用模板模式在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆