Welcome to AspAdvice Sign in | Join | Help

Thread safe singleton pattern with C#: easy!

Read here: http://www.dofactory.com/Patterns/PatternSingleton.aspx

Here is the classical maneer a thread-safe singleton is written in C#:

class MySingleton
{    
    private static MySingleton instance;    
    // Lock synchronization object    
    private static object syncLock = new object();    
    
    private MySingleton() { DoSomething(); }    
    
    public static MySingleton Instance    
    {        
        get        
        {            
            // Support multithreaded applications            
            // through 'Double checked locking'            
            // pattern which (once the instance            
            // exists) avoids locking each            
            // time the method is invoked            
            if (instance == null)            
            {                
                lock (syncLock)                
                {                    
                    if (instance == null)                        
                        instance = new MySingleton();                
                }            
            }            
            return instance;        
        }    
    }
}

And now, the ".NET" way:

class MySingleton
{   
    // Static members are lazily initialized.   
    // .NET guarantees thread safety for   
    // static initialization   
    private static readonly MySingleton instance =                       
        new MySingleton();  

    // Constructor (private)   
    private MySingleton() { DoSomething(); }   
   
    public static Instance { get { return instance; } }
}

This works because "private static readonly" involves:

  • lazy initialization
  • thread safety guaranteed by .NET for static initializations.
Ain't it beautiful?

Published Tuesday, July 25, 2006 11:59 PM by odalet

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Thread safe singleton pattern with C#: easy!

Wednesday, February 20, 2008 9:14 AM by Guus Beltman
Nice code fragment. Only 1 correction needed: public static Instance { get { return instance; } } should be: public static MySingleton Instance { get { return instance; } }

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below