Home > .Net, Design > Simple singleton pattern with inheritance in C#.NET (part 2)

Simple singleton pattern with inheritance in C#.NET (part 2)

In my previous post about singleton inheritance, I’ve presented a simple singleton design pattern implementation in C#.NET, and a more advance implementation method, which allows to inherit from base singleton class. In the curent post, I will show several ways, to make the singleton thread-safe.
While saying “thread-safe singleton”, one usually means the singleton creation; another functions/properties are handled regular way to be threadsafe. Singleton creation must take place only once.
Classic pattern, providing a solution for this issue, is double-checked locking. Why 2 checks are needed? Because, after the first time creation, the lock is redundant. So we just prevent it by additional check. Using this pattern, singleton creation looks like this:

class Keyboard 
{     
        private static Keyboard m_instance;
        private static object m_syncObject;

        private Keyboard() { m_syncObject = new object(); }       
        
        public static Instance     
        {         
                get        
                {
                        if (m_instance == null)
                        {
                                lock (m_syncObject)
                                {
                                        if (m_instance == null)                 
                                                m_instance = new Keyboard();
                                }
                        }     
                        return m_instance;         
                }
        } 
} 

This pattern works, but it is “fragile” – if some hypotetic system has different memory management, it could be failed. Sometimes it is even referenced as “anti-pattern”. Though, I do not agree with this: double-checked locking is being working in different systems, wroten in different languiges for a long time. Still, there are more simple and readable ways, particulary in C#.NET. Let’s see them…

To be continued…

Categories: .Net, Design Tags: , , ,
  1. March 27th, 2011 at 11:33 | #1

    you have a spelling error: agry => agree

  1. December 2nd, 2011 at 23:03 | #1