在 C# 中实现 Singleton

评论2次阅读2009.12.23 12:51; 作者:Felicia 

我们需要只有一个实例的类,并且需要提供一个用于访问实例的全局访问点,还希望确保解决方案是线程安全的。

下面的实现仅允许一个线程在尚未创建 Singleton 实例的情况下进入关键区域(该区域由 lock 块标识)。

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;
      
}
  
}
}

相关文章

  • 评论 (0)
  • 引用通告 (0)
发表评论 引用通告

暂无评论.

暂无引用通告